std::enable_if ... 又名 typename_if_else

std::enable_if ... else aka typename_if_else

类似于 std::enable_if 我想要一个 else 类型信息(我需要这个用于依赖可变参数模板 static_cast)。我扩展了 standard 的可能实现如下:

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;

有没有办法摆脱不再需要的空结构(第一个定义)?

您可以为 false 创建部分模板专业化,并让 true 成为默认值。

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;

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

是的,多亏了 std::conditional,您甚至可以摆脱部分专业化:

#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;