哪些类型可以简单构造?
What types are trivially constructible?
我知道,许多类型(例如 POD 类型)都是可以默认构造的。但是除了空参数列表之外,参数列表中的 trivially constructible 是什么类型?例如,哪些类型可以从 int
简单构造?想不出来了。
C++17 (live demo) 中的 int
无法简单构造以下类型:
#include <type_traits>
struct X { int x; };
struct Y { Y(int) {} };
struct Z { Z(int) = delete; };
static_assert(std::is_trivially_constructible<X, int>::value == false);
static_assert(std::is_trivially_constructible<Y, int>::value == false);
static_assert(std::is_trivially_constructible<Z, int>::value == false);
平凡可构造的定义为从给定类型的值构造,不执行任何不被视为“平凡”的操作(参见第 2 段 here)。 int
是一个平凡可复制的类型,所以 int
是平凡可复制的。因此,std::is_trivially_constructible_v<int, int>
为真。
唯一可能的微不足道的操作是默认构造、复制构造和移动构造。因此,如果一组参数调用任何其他构造函数或执行任何其他操作作为执行该构造的一部分,则这样的调用不会是微不足道的。
Trivially constructible from Args...
被定义为从给定类型的值构造,它只执行被认为“微不足道”的操作。特别是语法 T obj(std::declval<Args>()...)
必须只调用“微不足道的”操作。
直到 C++17,唯一可能的微不足道的构造操作是默认构造、复制构造和移动构造。因此,如果一组参数调用任何其他构造函数或执行任何其他操作作为执行该构造的一部分,那么这样的调用就不会是微不足道的。因此,在 C++17 中,std::is_trivially_constructible_v<T, int>
只能在 T
= int
时为真(int
可以从自身复制)。
从 C++20 开始,它实现了 P0960 "Allow initializing aggregates from a parenthesized list of values" std::is_trivially_constructible_v<X, int>
is true. See live demo。这是因为语法 X obj(std::declval<int>())
只调用了一些简单的操作,满足了类型特征的要求。
我知道,许多类型(例如 POD 类型)都是可以默认构造的。但是除了空参数列表之外,参数列表中的 trivially constructible 是什么类型?例如,哪些类型可以从 int
简单构造?想不出来了。
C++17 (live demo) 中的 int
无法简单构造以下类型:
#include <type_traits>
struct X { int x; };
struct Y { Y(int) {} };
struct Z { Z(int) = delete; };
static_assert(std::is_trivially_constructible<X, int>::value == false);
static_assert(std::is_trivially_constructible<Y, int>::value == false);
static_assert(std::is_trivially_constructible<Z, int>::value == false);
平凡可构造的定义为从给定类型的值构造,不执行任何不被视为“平凡”的操作(参见第 2 段 here)。 int
是一个平凡可复制的类型,所以 int
是平凡可复制的。因此,std::is_trivially_constructible_v<int, int>
为真。
唯一可能的微不足道的操作是默认构造、复制构造和移动构造。因此,如果一组参数调用任何其他构造函数或执行任何其他操作作为执行该构造的一部分,则这样的调用不会是微不足道的。
Trivially constructible from Args...
被定义为从给定类型的值构造,它只执行被认为“微不足道”的操作。特别是语法 T obj(std::declval<Args>()...)
必须只调用“微不足道的”操作。
直到 C++17,唯一可能的微不足道的构造操作是默认构造、复制构造和移动构造。因此,如果一组参数调用任何其他构造函数或执行任何其他操作作为执行该构造的一部分,那么这样的调用就不会是微不足道的。因此,在 C++17 中,std::is_trivially_constructible_v<T, int>
只能在 T
= int
时为真(int
可以从自身复制)。
从 C++20 开始,它实现了 P0960 "Allow initializing aggregates from a parenthesized list of values" std::is_trivially_constructible_v<X, int>
is true. See live demo。这是因为语法 X obj(std::declval<int>())
只调用了一些简单的操作,满足了类型特征的要求。