泛型编程 学习笔记

#include "iostream"

using namespace std;

template<typename T>
void Print(T a) {
	cout << a << endl;
}

int main() {
	int a = 5;
	double b = 2.3;
	char c = 'e';
	string d = "sdfasd";

	Print(a);
	Print(b);
	Print(c);
	Print(d);

	return 0;
}

它可以不用Print<类型>(参数);

直接用就能直接推导,从另一种形式来讲,模板是更高级的重载

但是,在类中就不适用,不能自动推导,在C++17开始才能自动推导,以上代码才不会报错


为什么12行Print会报错呢,因为Print没有参数可以推导T的类型,所以必须显示的指定类型,例如int


#include "iostream"

using namespace std;

template<typename T>
void Print(T a = 123) {
	cout << a << endl;
}

int main() {
	Print<int>();
	Print<string>();

	return 0;
}

当参数有默认值的时候,必须类型匹配才能不输入参数 


#include "iostream"

using namespace std;

template<typename T, int T1 = 23>
void Print(T a = 123) {
	cout << a << " " << T1 << endl;
}

int main() {
	Print<int>();
	Print<int, 45>(44);
	Print<string>("fgsd");

	return 0;
}

作为模板也可以当作参数,一定支持整型、枚举以及指针,其它根据编译器情况可能有不同


函数里面不能做特化,类里面可以 


运算符重载:

#include "iostream"

using namespace std;

class Test {
public:
	Test(int c, int d) : a(c), b(d) {}
	const Test operator+(const Test& test) {
		return Test(this->a + test.a, this->b + test.b);
	}
	inline const int Geta() const { return a; }
	inline const int Getb() const { return b; }
private:
	int a;
	int b;
};

int main() {
	Test test1(10, 20);
	Test test2(30, 50);
	const Test&& test3 = test1 + test2;
	cout << test3.Geta()<< " " << test3.Getb() << endl;

	return 0;
}

template <typename Type>
	void PrintNotEdit(Type Value)
	{
		FString ValueAsString;
		if constexpr (std::is_same<Type, int>::value)
		{
			ValueAsString = FString::Printf(TEXT("%d"), Value);
		}
		else if constexpr (std::is_same<Type, float>::value)
		{
			ValueAsString = FString::Printf(TEXT("%f"), Value);
		}
		else if constexpr (std::is_same<FString, Type>())
		{
			ValueAsString = FString::Printf(TEXT("%s"), *Value);
		}
		if (GEngine)
		{
			GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, ValueAsString);
		}
	}

	template<typename T>
	void Printf(T t) {
		PrintNotEdit(t);
	}

	template<typename T, typename ...ARGS>
	void Printf(T t, ARGS... args) {
		PrintNotEdit(t);
		Printf(args...);
	}

这里必须用constexpr,因为模板要运行时态才能有具体内容,加constexpr该成编译就取值,就能做对应操作了

猜你喜欢

转载自blog.csdn.net/qqQQqsadfj/article/details/132384302