can I use SFINAE to selectively define a member variable in a template class?

Nowibananatzki picture Nowibananatzki · Aug 25, 2014 · Viewed 7.5k times · Source

So what I want to do is to create a template class which may or may not contain a member variable based on the template argument passed in. like following:

template<typename T, bool flag>
class base
{
   foov<std::enable_if<flag, T>::type> m_var;
};

the above code could not survive the compiler.

Does anyone know how I can achieve this?

Answer

RamblingMad picture RamblingMad · Aug 26, 2014

Have a base class with enabled/disabled members based on template parameters:

template<typename T, typename Enable = void>
class base_class;

// my favourite type :D
template<typename T>
class base_class<T, std::enable_if_t<std::is_same<T, myFavouriteType>::value>>{
    public:
        int some_variable;
};

// not my favourite type :(
template<typename T>
class base_class<T, std::enable_if_t<!std::is_same<T, myFavouriteType>::value>>{
    public:
        // no variable
};

template<typename T>
class derived_class: public base_class<T>{
    public:
        // do stuff
};

This should give you a nice way to enable/disable members based on type.