类型特性

类型特性定义一个编译时基于模板的结构,以查询或修改类型的属性。

试图特化定义于 头文件的模板导致未定义行为,除了 std::common_type 可依照其所描述特化。

定义于头文件的模板可以用不完整类型实例化,除非另外有指定,尽管通常禁止以不完整类型实例化标准库模板。

特性上的运算

变参的逻辑或元函数

std::disjunction

template struct disjunction; (1)(C++17 起)

组成类型特性 B... 的逻辑析取,等效地在特性序列上进行逻辑或。

特化 std::disjunction 有一个公开且无歧义的基类,即

若 sizeof...(B) == 0 ,则为 std::false_type ;否则若 B1, ..., BN 中有 bool(Bi::value) == true ,则为首个 Bi ,或者若无这种类型则为 BN 。

不隐藏 disjunction 和 operator= 以外的基类成员名,而它们在 disjunction 中无歧义地可用。

析取是短路的:若存在模板类型参数 Bi 满足 bool(Bi::value) != false,则实例化 disjunction::value 不要求 j > i 的 Bj::value 的实例化。

模板形参

B...-每个要实例化 Bi::value 的模板参数 Bi 必须可用作基类,且定义了可转换到 bool 的成员 value

辅助变量模板

template inline constexpr bool disjunction_v = disjunction::value; (C++17 起)

可能的实现

template struct disjunction : std::false_type { };

template struct disjunction : B1 { };

template

struct disjunction

: std::conditional_t> { };

注意

disjunction 的特化不需要继承自 std::true_type 或 std::false_type :它简单地继承自首个 B ,其 ::value 在显式转换为 bool 后为 true ,或在它们都转换为 false 时继承自最后的 B 。例如, std::disjunction, std::integral_constant>::value 为 2 。

disjunction 的短路实例化异于折叠表达式:如 (... || Bs::value) 的折叠表达式实例化 Bs 中的每个 B ,而 std::disjunction_v 一旦能确定值就停止实例化。这在之后的类型实例化代价高昂,或以错误的类型实例化能导致硬错误时特别有用。

调用示例

#include

#include

#include

namespace std

{

template struct disjunction : std::false_type { };

template struct disjunction : B1 { };

template< bool B, class T, class F >

using conditional_t = typename conditional::type;

template

struct disjunction

: conditional_t> { };

}

template

struct first_constructible

{

template

struct is_constructible_x : std::is_constructible

{

using type = T;

};

struct fallback

{

static constexpr bool value = true;

using type = void; // 若找不到内容则返回的类型

};

template

using with = typename std::disjunction...,

fallback>::type;

};

int main()

{

// OK :不实例化 is_constructible

std::cout << "std::is_same::with<>, std::string>::value: "

<< std::is_same::with<>, std::string>::value

<< std::endl;

std::cout << "std::is_same::with, std::string>::value: "

<< std::is_same::with, std::string>::value

<< std::endl;

std::cout << "std::is_same::with, void>::value: "

<< std::is_same::with, void>::value

<< std::endl;

return 0;

}

输出

std::is_same::with<>, std::string>::value: 1

std::is_same::with, std::string>::value: 1

std::is_same::with, void>::value: 1

精彩链接

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。