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

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

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

the above code could not stand the compiler.

Does anyone know how I can achieve this?

+5
source share
4 answers

You have a base class with members enabled / disabled based on template options:

 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 good way to enable / disable type based elements.

+10
source

I think this is what you are looking for.

The class template does not have member data by default.

 template<typename T, bool flag> class base { }; 

Add a class template specialization with element data.

 template<typename T> class base<T, true> { foov<T> m_var; }; 
0
source

I have a workaround for this. It probably looks ugly, but fixes some of my problems.

First, I define a type with zero size:

 typedef int zero[0]; 

Next, I create a macro:

 #ifndef VAR #define VAR(Enable,YourType,VarName) \ std::conditional< Enable,YourType,zero >::type VarName #endif 

Then a class like this:

 template < int Cond > class Foo { VAR(Cond == 0,int,var); void print() { if (!sizeof(var)) return; //... } }; 

When you use a var type result, check its size before using it. If the size is zero, it is invalid.

-1
source
 #pragma once #include <type_traits> template <typename T, bool D, typename Enabled=void> class Node; template <typename T, bool D> class Node<T, D, std::enable_if_t<D>> { public: Node(const T& v) : value(v) {} private: T value; Node* next = nullptr; }; template <typename T, bool D> class Node<T, D, std::enable_if_t<!D>> { public: Node(const T& v) : value(v) {} private: T value; Node* next = nullptr; Node* prev = nullptr; }; 

Single or double linked list of nodes based on Boolean flag

-1
source

Source: https://habr.com/ru/post/1201093/


All Articles