gpt4 book ai didi

c++ - 聚合类和不可行的构造函数模板

转载 作者:行者123 更新时间:2023-12-02 18:12:56 25 4
gpt4 key购买 nike

众所周知,在 C++20 中,具有用户声明的构造函数的类不是聚合的。

现在,考虑以下代码:

#include <type_traits>

template <bool EnableCtor>
struct test {
template <bool Enable = EnableCtor, class = std::enable_if_t<Enable>>
test() {}
int a;
};

int main() {
test<false> t {.a = 0};
}

GCC 和 CLang 都不会编译此代码。因此,尽管这里没有实例化构造函数,但该类不是聚合。

构造函数模板是否被视为“声明的构造函数”?标准对这种情况有何规定?

最佳答案

聚合的定义发生了很大变化,但这里的相关部分却相当稳定。 [dcl.init.aggr] 中的 C++20 措辞说:

An aggregate is an array or a class ([class]) with

  • no user-declared or inherited constructors ([class.ctor]),
  • no private or protected direct non-static data members ([class.access]),
  • no virtual functions ([class.virtual]), and
  • no virtual, private, or protected base classes ([class.mi]).

请注意,它只是说没有声明的构造函数,句号。关于构造函数对于类模板的特定特化是否可行并不是什么微妙的事情。根本就没有。

因此给出这样的事情:

template <bool B>
struct X {
int i;
X(int i) requires B;
};

X<false>仍然不是一个聚合,即使它唯一声明的构造函数对于该特化来说是不可行的。没关系。聚合性只是声明的一个属性。

关于c++ - 聚合类和不可行的构造函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72032281/

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