darkdragon
darkdragon

Reputation: 460

std::enable_if ... else aka typename_if_else

Similar to std::enable_if I would like to have an else type info (I need this for dependent variadic template static_cast). I extended the possible implementation from the standard as follows:

template<bool B, class T = void, class F = void>
struct typename_if_else
{};

template<class T, class F>
struct typename_if_else<true, T, F>
{
    typedef T type;
};

template<class T, class F>
struct typename_if_else<false, T, F>
{
    typedef F type;
};

template< bool B, class T = void >
using typename_if_else_t = typename typename_if_else<B,T>::type;

Is there a way to get rid of the empty struct (first definition) which is not needed any more?

Upvotes: 0

Views: 291

Answers (2)

nils
nils

Reputation: 338

You can create a partial template specialization for false, and let true be the default.

template<bool B, class T = void, class F = void>
struct typename_if_else
{
typedef T type;
};

template<class T, class F>
struct typename_if_else<false, T, F>
{
    typedef F type;
};

template< bool B, class T = void >
using typename_if_else_t = typename typename_if_else<B,T>::type;

Upvotes: 2

YSC
YSC

Reputation: 40070

Is there a way to get rid of the empty struct (first definition) which is not needed any more?

Yes, thanks to std::conditional you can even get rid of the partial specializations:

#include <type_traits>

template<bool B, class T = void, class F = void>
using typename_if_else = std::conditional_t<B, T, F>; // (can be omitted if you only care for typename_if_else_t)

template<bool B, class T = void>
using typename_if_else_t = typename typename_if_else<B,T>::type;

Upvotes: 1

Related Questions