gpt4 book ai didi

C++11 - 将非静态数据成员声明为 'auto'

转载 作者:太空宇宙 更新时间:2023-11-04 14:09:40 25 4
gpt4 key购买 nike

如果在声明中初始化非静态数据成员,C++11 是否允许将它们声明为“auto”?例如:

struct S
{
auto x = 5; // in place of 'int x = 5;', which is definitely allowed
};

GCC 4.7 拒绝上述代码,但它接受 int x = 5;

假设这不是编译器错误,而是标准确实不允许,为什么不呢?它与声明局部变量 auto 一样有用。

最佳答案

禁止非静态成员的规则在7.1.6.4第4条:

The auto type-specifier can also be used in declaring a variable in the condition of a selection statement (6.4) or an iteration statement (6.5), in the type-specifier-seq in the new-type-id or type-id of a new-expression (5.3.4), in a for-range-declaration, and in declaring a static data member with a brace-or-equal-initializer that appears within the member-specification of a class definition (9.4.2).

我发现它是静态的基本原理 here这反射(reflect)了 James McNellis 在评论中的解释。

One national body dislikes allowing the auto type-specifier for non-statics. From an e-mail to the authors:

    template< class T >
struct MyType : T {
auto data = func();
static const size_t erm = sizeof(data);
};

In order to determine the layout of X, we now have 2-phase name lookup and ADL. Note that func could be either a type or a function; it may be found in T, the namespace of MyType, the associated namespace(s) of T when instantiated, the global namespace, an anonymous namespace, or any namespaces subject to a using directive. With care we could probably throw some concept_map lookup in for luck. Depending on the order of header inclusion I might even get different results for ADL, and break the One Definition Rule - which is not required to be diagnosed.

Because of this controversy, the authors no longer propose that auto be allowed for non-static data members.

因此,基本上根据 header 包含的顺序,data 的类型可能会非常不同。当然,auto x = 5; 不需要依赖于两阶段名称查找或 ADL,但是,我假设他们将其设为“一揽子”规则,否则,他们会必须为每个用例制定单独的规则,这会使事情变得非常复杂。

在同一篇论文中,作者提议取消此限制,但是,该提议似乎已被拒绝,可能是由于上述理由,而且无论初始化程序是什么,预期行为都可以相同。

关于C++11 - 将非静态数据成员声明为 'auto',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15236533/

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