#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<type>(parameters) なしで使用できます。
別の形式では、テンプレートはより高度なオーバーロードです。
ただし、クラスには適用されず、自動的に派生することはできません。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 を追加すると、テンプレートがコンパイルされて値が取得され、対応する操作を実行できるようになります。