局部变量作为非类型参数,具有模板规范

local variable as non-type argument, with template specification

本文关键字:类型参数 局部变量      更新时间:2023-10-16

我有一个模板函数,以及枚举上的模板规范。我希望程序在运行时根据枚举的值选择模板规范。可能吗?

以下代码出错:

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
    }
}