Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing enum cast to int

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

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

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

like image 713
xis Avatar asked Aug 31 '11 21:08

xis


2 Answers

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

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);
like image 66
Lightness Races in Orbit Avatar answered Oct 22 '22 15:10

Lightness Races in Orbit


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.

like image 22
Ed Heal Avatar answered Oct 22 '22 14:10

Ed Heal