为什么type_traits实现与专门的模板结构而不是constexpr? [英] Why are type_traits implemented with specialized template structs instead of constexpr?
问题描述
有什么原因为什么标准将它们指定为模板 struct
s而不是简单布尔 constexpr
?
在另一个问题可能会回答一个好的回答主要问题,如何 enable_if
stuff非结构化版本?
一个原因是 constexpr
函数不能提供嵌套的类型
成员,这在某些元编程情况下非常有用。
很清楚,我不是只谈到产生类型的显然不能做<$ c $转换特性(例如 make_unsigned
c> constexpr 函数。 所有类型traits 提供这样的嵌套类型
成员,甚至一元类型特性 em>。例如 is_void< int> :: type
是 false_type
。
当然,这可以用 std :: integral_constant< bool,the_constexpr_function_version_of_some_trait< T>()>
来解决,但是它不会那么实用。
在任何情况下,如果你真的想要类似函数的语法,这是可能的。您只需使用traits构造函数,并利用 intl_constant $中的constexpr隐式转换c $ c>
:
static_assert(std :: is_void< void>(),void is void;谁会有thunk?);
对于转换traits ,您可以使用模板别名来获取该语法:
template< bool Condition,typename T = void>
使用enable_if = typename std :: enable_if< Condition,T> :: type;
//用法:
// template< typename T> enable_if< is_void< T>(),int> F();
//
// make_unsigned< T> X;
Is there any reason why the standard specifies them as template struct
s instead of simple boolean constexpr
?
In an additional question that will probably be answered in a good answer to the main question, how would one do enable_if
stuff with the non-struct versions?
One reason is that constexpr
functions can't provide a nested type
member, which is useful in some meta-programming situations.
To make it clear, I'm not talking only of transformation traits (like make_unsigned
) that produce types and obviously can't be made constexpr
functions. All type traits provide such a nested type
member, even unary type traits and binary type traits. For example is_void<int>::type
is false_type
.
Of course, this could be worked around with std::integral_constant<bool, the_constexpr_function_version_of_some_trait<T>()>
, but it wouldn't be as practical.
In any case, if you really want function-like syntax, that is already possible. You can just use the traits constructor and take advantage of the constexpr implicit conversion in integral_constant
:
static_assert(std::is_void<void>(), "void is void; who would have thunk?");
For transformation traits you can use a template alias to obtain something close to that syntax:
template <bool Condition, typename T = void>
using enable_if = typename std::enable_if<Condition, T>::type;
// usage:
// template <typename T> enable_if<is_void<T>(), int> f();
//
// make_unsigned<T> x;
这篇关于为什么type_traits实现与专门的模板结构而不是constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!