是否可以通过模板创建变量类型下标的数组?
Is it possible to create an array with subscripts of variable type through the template?
可能会这样使用
str<int> = "int";
num<double> = 2;
cout << str<int> << endl; // output "int"
cout << num<double> << endl; // output 2
是的,声明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
}
可能会这样使用
str<int> = "int";
num<double> = 2;
cout << str<int> << endl; // output "int"
cout << num<double> << endl; // output 2
是的,声明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
}