我有一个模板函数,以及一个枚举模板规范。我希望程序在运行时根据枚举的值选择模板规范。可能吗?
以下代码出错:
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;
}
最佳答案
I want the program to choose the template specification based on the value of enum at runtime.
不,那是不可能的。模板非类型参数必须在编译时可用。如果直到运行时你才知道你的值,你只能将它作为函数参数传递。
正如 TC 所建议的,您可以做的是切换
所有可能的值,并使用编译时常量显式调用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++ - 作为非类型参数的局部变量,具有模板规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27914841/