Question

My platform is Windows with Visual Studio Express 2012.

I have a templated method as follows

struct A 
{
    template<class T> void blub(T value);
};

I want to have several specializations like the following:

template<> void A::blub(std::string value) { /* ... */ }
template<> void A::blub(int value) { /* ... */ }

However, now I'd like to include enums, somehow like this:

enum MyEnum { ENUM_1 };

A a;
a.blub(ENUM_1);

This fails, of course, because there's no specialization for that type. I don't know the exact enum in advance, so I'd like to derive a template specialization for enums in general.

Doing something like the following will fail compiling:

template<class T> void A::blub(const typename std::enable_if<std::is_enum<T>::value, T>::type& value) { /* ... */ }

The compiler fails with C2244. This makes sense, because the compiler can't deduce the type for that method in general.

Which gets me to the conclusion: what I want is not possible. For the above call I would have to make the following:

A a;
a.blub((int)ENUM_1);

Is my conclusion right? I just have to do the cast in the call? A workaround would be to template the class, but I don't want to do this, because the class does do a lot of other things apart from that method.

Was it helpful?

Solution

Your attempt tries to partialy specialize a function template - that's not allowed. Do it like this instead, on the return type:

struct A
{
    template<typename T>
    typename std::enable_if<std::is_enum<T>::value>::type
    blub(T value);

    // and don't specialize for concrete types,
    // just overload:

    void blub(std::string value);
    void blub(int value);
};

Live example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top