局部变量作为非类型参数,具有模板规范
local variable as non-type argument, with template specification
我有一个模板函数,以及枚举上的模板规范。我希望程序在运行时根据枚举的值选择模板规范。可能吗?
以下代码出错:
error C2971: 'Func' : template parameter 'fruit' : 'fruit' : a local variable cannot be used as a non-type argument
法典:
enum class Fruit
{
Apple,
Orange,
Count
};
template<Fruit>
void Func()
{}
template<>
void Func<Fruit::Apple>()
{
std::cout << "Apple" << std::endl;
}
template<>
void Func<Fruit::Orange>()
{
std::cout << "Orangle" << std::endl;
}
void Foo(Fruit fruit)
{
Func<fruit>(); // error C2971: 'Func' : template parameter 'fruit' : 'fruit' : a local variable cannot be used as a non-type argument
}
int _tmain(int argc, _TCHAR* argv[])
{
Foo(Fruit::Apple);
return 0;
}
我希望程序在运行时根据枚举的值选择模板规范。
不,这是不可能的。模板非类型参数必须在编译时可用。如果在运行时之前没有值,则只能将其作为函数参数传入。
正如 TC 所建议的那样,您可以做的是对所有可能的值进行switch
,并使用编译时常量文本显式调用Func
:
void Foo(Fruit fruit)
{
switch (fruit) {
case Fruit::Apple:
Func<Fruit::Apple>();
break;
case Fruit::Orange:
Func<Fruit::Orange>();
break;
// .. maybe other fruits here
}
}
相关文章:
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 将共享指针传递给函数参数 - 将其分配给局部变量的正确方法是什么
- 如何在 C++ 的 lambda 函数中传递同名的局部变量和参数(使用此关键字)?
- 在返回参数列表中C++局部变量(如CodeFights所示)
- 为什么不能在模板函数中向局部变量添加低级 const 类型
- 解析参数值 - 字符串和链接值(类型字符串的链接值)与(特定类型的)变量
- 在 pthread_create() 中使用局部变量作为参数有效吗?
- 使用函数模板中静态局部变量的地址作为类型标识符是否安全
- 使用局部变量中的类成员类型
- 指针或局部变量,用于函数的输出参数
- C 11-当我将局部变量作为参数传递到线程中时,它是否安全
- 返回取决于sizeof的变量类型..参数包
- 通过引用参数将局部变量分配给
- 如何将带有局部变量的一些参数的函数包装器放入具有MSVC2015的容器中
- C++ 对局部变量的引用与对参数的引用
- 局部变量作为非类型参数,具有模板规范
- 为什么我不能将局部变量的引用作为非类型模板参数?
- 如何访问函数内部Mat类型参数的变量名
- 在程序中使用非类型模板参数而未给局部变量赋值时,会导致意外结果
- 局部变量作为非类型模板参数