c++ - 类型到值元函数可以用作 C++14 中的变量别名吗?

标签 c++ typetraits c++14 template-aliases variable-templates

在查看 C++14 元函数别名提案(TransformationTraits Redux, v2,N3655)时,我注意到,不仅类型到类型转换(例如 add_const),类型到值元函数(例如 is_void)也是类型别名。 (在 N3797 中不存在)。

使用别名类型来赋值元函数有什么好处吗?我认为,可以在没有这些别名的情况下使用它们,例如存在转换操作时的 enable_if_t<is_void<T>::value,T>enable_if_t<is_void<T>{}(),T>。 (我猜 is_void<T>::type::valueis_void<T>::value 一样)

如果值元函数的类型需要别名,将它们别名为变量模板不是更好吗(我没有 C++14 编译器,也从未使用过变量模板。所以语法可能是错误的)?例如别名 is_void

template <class T>
constexpr bool is_void_t = is_void<T>::value;

代替

template <class T>
using is_void_t = typename is_void<T>::type;

然后可以不用boost样式写enable_if_t<is_void_t<T>,T> enable_if ,写表达式会更容易(例如enable_if_t<(is_void_t<T> || is_integral_t<T>),T>

最佳答案

“给元函数赋值的别名类型有什么优势吗?”

引用自链接的 N3655,在 is_void_t 的规范之前和 sibling (第 4 页):

4   Supplementary proposed wording

The following wording is provided in response to LWG’s request that aliases for ::type members be consistently provided for all the type traits, not only for those classified as TransformationTraits. Accordingly, this section provides the specifications needed in order to complete the set.

这解释了为什么在提案中“键入值元函数(例如 is_void)也是类型别名”:为了保持一致性。

此外,使用名称“is_void_<b>t</b>”也是错误的。 ” 别名 is_void<T>::<b>value</b> . “_t ” 后缀始终表示类型。对于值,也许可以使用“ _v ”后缀。所以我们将同时拥有:

template <class T>
using is_void_t = typename is_void<T>::type;

template <class T>
constexpr bool is_void_v = is_void<T>::value;

那应该在 C++14 中编译,然后你可以写类似 enable_if_t<(is_void_v<T> || is_integral_v<T>),T> 的东西.但是我觉得值别名比类型别名“不需要”:它不会节省那么多输入,而且正如您所说,您可以使用短 is_void<T>{}()具有相同的效果(对于 C++11,is_void<T>{} 通常就足够了,这要归功于它的 operator bool() )。

关于c++ - 类型到值元函数可以用作 C++14 中的变量别名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20297284/

相关文章:

c++ - "constexpr if"vs "if"优化 - 为什么需要 "constexpr"?

c++ - 引用性与模板函数中的类型无关

c++ - 如何判断一个类型是否真正可 move 构造

c++ - 如何使用递归打印在 0/1 背包问题中选择的元素

c++ - 未命名命名空间内名称的外部链接

可能需要引用的 C++ 模板函数

c++ - 为什么不能简单地初始化(带大括号)2D std::array?

c++ - 如何乘法和除法一天中的时间,例如10 :00 and 5:00 with overloaded functions?

c++ - Qmysql 驱动未加载但可用

c++ - 如何在类范围内定义/专门化 type_trait?