'typename Enable = void'是什么意思?

zan*_*ngw 9 c++ templates

我发现typename Enable = void在定义protobuf的,

template<typename T, typename Enable = void>
struct RefTypeTraits;
Run Code Online (Sandbox Code Playgroud)

但是,我找不到Enable在这个头文件中使用的,这让我很困惑.typename Enable = void模板中的含义是什么?

Jar*_*d42 6

这是为了让SFINAE具有模板专业化,就像它一样

template<typename T>
struct RefTypeTraits<T, std::enable_if_t<some_condition<T>::value>> {
    // ... specialization for T which respects condition
};
Run Code Online (Sandbox Code Playgroud)

  • @Thomson:“std::enable_if_t&lt;condition_v&lt;T&gt;&gt;”在成功时转换为“void”,但在失败时,而不是错误,该专业化只是被丢弃。 (2认同)

Vau*_*ato 5

您的模板只有两个模板参数。第二个称为“启用”,它的默认类型为“无效”。这是稍后允许SFINAE 的一个技巧。