【发布时间】:2020-10-18 00:26:54
【问题描述】:
可以这样使用
str<int> = "int";
num<double> = 2;
cout << str<int> << endl; // output "int"
cout << num<double> << endl; // output 2
【问题讨论】:
标签: c++ templates template-meta-programming c++20
可以这样使用
str<int> = "int";
num<double> = 2;
cout << str<int> << endl; // output "int"
cout << num<double> << endl; // output 2
【问题讨论】:
标签: c++ templates template-meta-programming c++20
是的,如下声明str和num
template <typename>
std::string str;
template <typename>
int num;
是模板变量,从 C++14 开始可用。
但要考虑到所有str 变量的类型为std::string,并且所有num 变量的类型为int。
正如 Davis Herrings 所指出的,使用专业化(部分或完全专业化)可以缓解这个问题。例如,如果你希望str<some-type>,对于泛型类型some-type,是一个整数值,除了str<int>,它必须是std::string,你可以如下声明它
template <typename>
int str;
template <>
std::string str<int>;
以下是完整的编译示例
#include <iostream>
template <typename>
std::string str;
template <typename>
int num;
int main ()
{
str<int> = "int";
num<double> = 2;
std::cout << str<int> << std::endl; // output "int"
std::cout << num<double> << std::endl; // output 2
}
【讨论】:
typename,模板参数可以是template <typename...> class; template <template <typename...> class> std::string str; 之类的东西。应该与几乎所有 STL 容器兼容(但不幸的是,不兼容 std::array)。