Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ enable_if (or workaround) for member operator

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 don't want to implement the operator*(). How can I achieve this? I don't 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 issue.

like image 821
0xbadf00d Avatar asked Dec 06 '22 22:12

0xbadf00d


1 Answers

You can move all the other methods (which play well with T==void) into a base class and make foo derive from it. Then foo can be specialized to not declare the 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> {

};
like image 115
Alexander Gessler Avatar answered Dec 27 '22 06:12

Alexander Gessler