Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forming reference to void

Tags:

c++

templates

I have a template class that should allow void as a template parameter. This class does have a function that passes a reference of the parameter, so I did the following:

template <typename T>
struct trait
{
    typedef typename boost::conditional<
        boost::is_void<T>::value,
        void, T &
    >::type type;
};

template <typename T>
struct foo
{
    typename trait<T>::type ref()
    {
        // do something
    }
};

Yet the compiler claims I would form a reference to void in instantiation of struct trait<void>. Why so and how can I achieve what I want?

like image 497
nijansen Avatar asked Oct 19 '12 05:10

nijansen


1 Answers

Well, you clearly form a reference to void in your conditional type definition when you say T&. This seems to be best dealt with a specialization:

template <typename T> struct trait { typedef T& type; };
template <> struct trait<void> { typedef void type; };
like image 120
Dietmar Kühl Avatar answered Oct 02 '22 00:10

Dietmar Kühl