Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 934
Nowibananatzki Avatar asked Aug 25 '14 18:08

Nowibananatzki


1 Answers

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.

like image 87
RamblingMad Avatar answered Oct 11 '22 02:10

RamblingMad