类型特性
类型特性定义一个编译时基于模板的结构,以查询或修改类型的属性。
试图特化定义于 <type_traits> 头文件的模板导致未定义行为,除了 std::common_type 可依照其所描述特化。
定义于<type_traits>头文件的模板可以用不完整类型实例化,除非另外有指定,尽管通常禁止以不完整类型实例化标准库模板。
特性上的运算
逻辑非元函数
std::negation
template<class B> | (1) | (C++17 起) |
构建类型特性 B
的逻辑否定。
类型 std::negation<B> 是基特征 (BaseCharacteristic) 为 std::bool_constant<!bool(B::value)> 的一元类型特征 (UnaryTypeTrait) 。
模板形参
B | - | 使得表达式 bool(B::value) 为合法常量表达式的任何类型 |
辅助变量模板
template<class B> | (C++17 起) |
可能的实现
template<class B>
struct negation : std::bool_constant<!bool(B::value)> { };
继承自 std::integral_constant
成员常量
value [静态] | 若 B 拥有在隐式转换为 bool 时等于 false 的 ::value 则为 true ,否则为 false(公开静态成员常量) |
成员函数
operator bool | 转换对象为 bool ,返回 value (公开成员函数) |
operator() (C++14) | 返回 value (公开成员函数) |
成员类型
类型 | 定义 |
value_type | bool |
type | std::integral_constant<bool, value> |
调用示例
#include <iostream>
#include <type_traits>
namespace std
{
template <bool B>
using bool_constant = integral_constant<bool, B>;
template<class B>
struct negation : std::bool_constant < !bool(B::value) > { };
}
int main()
{
std::cout << std::boolalpha;
std::cout << "std::negation<std::bool_constant<true>>::value: "
<< std::negation<std::bool_constant<true>>::value << std::endl;
std::cout << "std::negation<std::bool_constant<false>>::value: "
<< std::negation<std::bool_constant<false>>::value << std::endl;
return 0;
}
输出
std::negation<std::bool_constant<true>>::value: false
std::negation<std::bool_constant<false>>::value: true