开发者

C++ enable_if (or workaround) for member operator

template<typen开发者_运维知识库ame 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.


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> {

};


The C++11 standard solved this for std::unique_ptr like so:

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


Like that:

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>
{
};


How about

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

or am I missing something obvious here?


What's 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜