gpt4 book ai didi

c++ - 类型特征上的不同编译器行为来测试隐式默认可构造性

转载 作者:太空狗 更新时间:2023-10-29 20:53:45 25 4
gpt4 key购买 nike

我一直在尝试用 C++11/14 编写一个类型特征来判断类型是否为 T是隐式默认构造的。隐式/显式默认可构造类型的示例:

struct Imp { Imp() = default; };
struct Exp { explicit Exp() = default; };

Imp i = {}; // ok
Exp e = {}; // error

我知道这个特性一定可以用 C++17 实现,因为 std::tuple<Ts...> 的默认构造函数是明确的当且仅当不是所有Ts...是隐式默认可构造的。所以我想知道委员会对其可能的实现有何想法。

我试过的是这样的:

#include <type_traits>

template<typename T>
struct IsImplicitlyDefaultConstructible {
private:
template<typename U> static void helper(const U&);
template<typename U> static std::true_type test(decltype(helper<U>({}))*);
template<typename U> static std::false_type test(...);

public:
static constexpr bool value = decltype(test<T>(0))::value;
};

struct Yes { Yes() = default; };
struct No { explicit No() = default; };

int main()
{
static_assert(IsImplicitlyDefaultConstructible<Yes>::value, "");
static_assert(!IsImplicitlyDefaultConstructible<No>::value, "");
}

想法是测试是否{}可转换为 const T& .奇怪的是,上面的代码在 GCC 6.1+ 上运行,但在 GCC 4/5 和所有版本的 Clang 和 CL 上运行失败。查看演示 here .

那么发生了什么?这是 GCC 6.1+ 或其他版本中的错误吗?我怎样才能使这个特性起作用(最好使用 C++11,但如果需要 C++14 也可以)?

最佳答案

您的测试用例失败的每个编译器也接受No n = {};

直到recently ,具有显式默认构造函数不会阻止类成为聚合。

聚合的

{} 执行聚合初始化并且不调用任何构造函数,无论是显式的还是其他方式。因此没有错误,因为代码不会尝试在这些编译器中调用显式构造函数。

关于c++ - 类型特征上的不同编译器行为来测试隐式默认可构造性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41799015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com