Generic programming study notes

#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;
}

It can be used without Print<type>(parameters);

It can be directly deduced directly. In another form, the template is a more advanced overload

However, it is not applicable in the class, and cannot be automatically derived. It can only be automatically derived from C++17, and the above code will not report an error


Why does the 12-line Print report an error, because Print has no parameters to deduce the type of T, so the specified type must be displayed, such as 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;
}

When the parameter has a default value, the type must match to not enter the parameter 


#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;
}

As a template, it can also be used as a parameter. It must support integers, enumerations, and pointers. Others may vary depending on the compiler.


Specialization cannot be done in a function, but can be done in a class 


Operator overloading:

#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 must be used here, because the template can only have specific content when it is running. Adding constexpr should make it compile and take the value, and you can do the corresponding operation.

Guess you like

Origin blog.csdn.net/qqQQqsadfj/article/details/132384302