C ++ enable_if (or workaround) for member statement

template<typename T> struct foo { T* p; foo(T* x) : p(x) {} ~foo() { if(p) delete p; } T& operator*() const { return *p; } }; int main() { foo<int> i(new int); foo<void> v(new int); // <= illegal use of type 'void' } 

If T = void, then I do not want to implement the * () operator. How can i achieve this? I do not want to specialize the class because there are many other methods in my class.

PS: Please note that this is just an example to explain my problem.

+4
source share
5 answers

The C ++ 11 standard solved this for std::unique_ptr as follows:

 typename std::add_lvalue_reference<T>::type operator*() const { return *p; } 
+5
source

You can move all the other methods (which work well with T==void ) to the base class and make foo out of it. Then foo can be specialized so as not to declare an operator* for T==void

 template <typename T> struct foobase { T* p; foobase(T* x) : p(x) {} ~foobase() { if(p) delete p; } }; template <typename T> struct foo : foobase<T> { T& operator*() const { return *p; } }; template<> struct foo<void> : foobase<void> { }; 
+6
source

Like:

 template<typename T> struct foo_base { T* p; foo(T* x) : p(x) {} ~foo() { if(p) delete p; } // other methods â€Ļ }; template<typename T> struct foo : foo_base<T> { T& operator*() const { return *p; } }; template<> struct foo<void> : foo_base<void> { }; 
+3
source

What about

 typename disable_if<is_void<T>, T>::type& operator* () const { return *p;} 

or am i missing something obvious here?

+1
source

How about this solution:

 template<typename T> struct foo { T* p; foo(T* x) : p(x) {} ~foo() { if(p) delete p; } template<typename U> struct impl { U& deref(U* p) { return *p; } }; template<> struct impl<void> { void deref(void* p) { } }; typename boost::conditional<std::is_void<T>::value, T, typename std::add_reference<T>::type>::type operator*() const { static_assert(!std::is_void<T>::value, "illegal use of type 'void'"); return impl<T>().deref(p); } }; 
0
source

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


All Articles