C++ 的 模板特化
等级 5525 次按键
通过完全特化(template<>)为 Serializer 提供 int 和 string 专用的实现,其他类型使用通用的主模板。double 没有特化,因此得到“[object]”。
C++ 代码
// 主模板:用于所有没有特化的类型1template<typename T>2class Serializer {3public: // 通用的默认结果4 static string serialize(const T& value) {5 return "[object]";6 }7};8 // template<> 表示完全特化9template<>// 仅当 T 为 int 时使用的版本10class Serializer<int> {11public:12 static string serialize(int value) { // to_string 把数字转换为文本13 return "int:" + to_string(value);14 }15};16 17template<>// 仅当 T 为 string 时使用的版本18class Serializer<string> {19public:20 static string serialize(const string& value) { // 用双引号包住值21 return "string:\"" + value + "\"";22 }23};24 // 使用 int 特化:输出“int:42”25cout << Serializer<int>::serialize(42) << endl;// “hello”被转换为 string:输出 string:"hello"26cout << Serializer<string>::serialize("hello") << endl;// double 没有特化:主模板输出“[object]”27cout << Serializer<double>::serialize(3.14) << endl;运行结果
int:42 string:"hello" [object]
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 C++ 代码中需要输入的符号及其出现次数。
<× 20"× 12:× 11;× 9>× 8(× 7)× 7{× 6}× 6+× 3