C++ 将枚举转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7263672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:42:23  来源:igfitidea点击:

Doing enum cast to int

c++templatescastingenums

提问by xis

I've a problem on this code:

我对这段代码有问题:

template <typename T>
void dosth(T& value,const T& default_value)
{
   if (condition)
       value = 10;
   else
       value = default_value;
}

When I call that with

当我用

enum {
    SITUATION1,
    STIUATION2
};

int k;
dosth(k,SITUATION1);

the compiler (g++ 4.5) says

编译器(g++ 4.5)说

no matching function for call to 'dosth(int&,)'

没有用于调用“dosth(int&,)”的匹配函数

Why doesn't the compiler automatically cast the enum into an int?

为什么编译器不自动将枚举转换为 int?

回答by Lightness Races in Orbit

Your problemis due to the fact that the template cannot be instantiated from the function arguments that you supply. No implicit conversion to intoccurs, because there's no function to call at all.

您的问题是由于无法从您提供的函数参数实例化模板。没有隐式转换int时,因为没有要调用的函数在所有

If you cast instead of attempting to rely on implicit conversion, your program will work:

如果您强制转换而不是尝试依赖隐式转换,您的程序将工作

dosth(k, static_cast<int>(SITUATION1));

Or, if you provide the function template's arguments explicitly, then the function argument will be converted implicitly as you expect, and your program will work:

或者,如果您显式提供函数模板的参数,则函数参数将按照您的预期进行隐式转换,您的程序将正常工作

dosth<int>(k, SITUATION1);

回答by Ed Heal

Would this be better for enums?

这对枚举会更好吗?

class Situations
{
  private:
    const int value;
    Situations(int value) : value(value) {};
  public:
    static const Situations SITUATION1() { return 1; }
    static const Situations SITUATION2() { return 2; }
    int AsInt() const { return value; }
};

Will enable type safety. Then use it to create a type safte template.

将启用类型安全。然后用它来创建一个类型安全模板。

i.e. Value for pass or fail.

即通过或失败的值。