Adr*_*ian 7 c++ metaprogramming template-meta-programming c++11
我有一个模板函数,其中枚举类型转换为其基础类型,工作正常,但我写了一个重载应该采取整数并返回自己,它给我一个错误,int不是枚举类型.在我的模板中,这应该已被过滤掉.怎么了?
这是模板代码:
template <typename TT>
static constexpr auto get_value(TT t)
-> typename std::enable_if<!std::is_enum<TT>::value, TT>::type
{
return t;
}
template <typename TT>
static constexpr auto get_value(TT t)
-> typename std::enable_if<std::is_enum<TT>::value, typename std::underlying_type<TT>::type>::type
{
return (typename std::underlying_type<TT>::type)t;
}
Run Code Online (Sandbox Code Playgroud)
std::underlying_type<TT>::type正在评估,std::enable_if即使std::is_enum<TT>::valueis falseasfalse不是错误。由于正在评估非枚举类型,因此会导致错误。如果我们将 SFINAE 移到模板参数中,我们可以获得所需的重载,并且仍然返回正确的类型。
template <typename TT, typename std::enable_if<!std::is_enum<TT>::value, TT>::type* = nullptr>
static constexpr auto get_value(TT t) -> TT
{
return t;
}
template <typename TT, typename std::enable_if<std::is_enum<TT>::value>::type* = nullptr>
static constexpr auto get_value(TT t) -> typename std::underlying_type<TT>::type
{
return (typename std::underlying_type<TT>::type)t;
}
Run Code Online (Sandbox Code Playgroud)
你可以看到它在这个中工作Live Example
| 归档时间: |
|
| 查看次数: |
215 次 |
| 最近记录: |