我有一个模板函数,以及一个枚举上的模板规范。我希望程序基于运行时枚举的值来选择模板规范。有可能吗?
以下代码出错:
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;
}发布于 2015-01-13 04:24:02
我希望程序基于运行时枚举的值来选择模板规范。
不那是不可能的。模板非类型参数必须在编译时可用。如果直到运行时才有值,则只能将其作为函数参数传入。
正如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
}
}https://stackoverflow.com/questions/27914841
复制相似问题