具有枚举专业化的模板

时间:2021-02-24 12:44:56

标签: c++ templates enums

我有一个模板,它将枚举类作为专业化(注意枚举的不同初始化),我希望能够比较两个不同的枚举

enum choiceA {One, Two, Three};
typedef enum  {Four, Five, Six} choiceB;

template<typename S>
void f(S choice, int& x)
{
if (choice == One || choice == Four) { x = SomeWhateverIntegerValue;}
else if(choice = Five) {x = AnOtherWhateverIntegerValue;}
else {x = OtherIntegerValue;}
}

这样

int x = 0;
f<choiceA>(One, x);

按预期工作。

1 个答案:

答案 0 :(得分:3)

同一个枚举有两种枚举类型这一事实很奇怪。我会先修复那个设计。

无论如何,要严格回答您的问题,您在这里不需要模板。一个简单的重载就足够了:


void f(choiceA choice, int& x)
{
    if (choice == One)
    {
        x = SomeWhateverIntegerValue;
    }
    else
    {
        x = OtherIntegerValue;
    }
}

void f(choiceB choice, int& x)
{
    if (choice == Four)
    {
        x = SomeWhateverIntegerValue;
    } else if(choice == Five)
    {
        x = AnOtherWhateverIntegerValue;
    }
    else
    {
        x = OtherIntegerValue;
    }
}

作为旁注,避免使用 C 风格的 typedef enum/class { ... } Name;

还要注意 if(choice = Five) 你有一个危险的拼写错误。它应该是 ==。启用编译器警告,大多数现代编译器都会对此发出警告。

相关问题