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?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With