gpt4 book ai didi

c++ - 为什么会有注入(inject)的类名?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:34 25 4
gpt4 key购买 nike

最近,我看到了一个奇怪的 C++ 特性:注入(inject)类名

class X { };
X x1;
class X::X x2; // class X::X is equal to X
class X::X::X x3; // ...and so on...

但我不明白为什么需要此功能。是否有任何实践需要此功能?

而且我听说旧 C++ 中不存在此功能。那么,它是什么时候推出的呢? C++03? C++11?

最佳答案

注入(inject)的类名表示X被声明为 X 的成员, 所以里面的名字查找 X总是找到当前类,而不是另一个 X可能在相同的封闭范围内声明,例如

void X() { }
class X {
public:
static X create() { return X(); }
};

create()创建临时函数 X对象或调用函数 X ?在命名空间范围内,它会调用该函数,因此注入(inject)类名的目的是确保在 X 的主体内名称总是找到类本身(因为名称查找在查找封闭范围之前在类自己的范围内开始)。

它在类模板中也很有用,注入(inject)的类名可以在没有模板参数列表的情况下使用,例如简单地使用 Foo而不是完整的模板 ID Foo<blah, blah, blah> , 所以很容易引用当前的实例化。参见 DR 176 C++98 和 C++03 之间的变化澄清了这一点。

注入(inject)类名的概念出现在 C++98 中,但这个术语对于 C++03 来说是新的。

C++98 说:

A class-name is inserted into the scope in which it is declared immediately after the class-name is seen. The class-name is also inserted into the scope of the class itself.

第二句被DR 147改了所以 C++03 在 [class]/2 中说:

A class-name is inserted into the scope in which it is declared immediately after the class-name is seen. The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name.

甚至在 C++98 之前,ARM 就有大致相同的措辞,这意味着类的名称总是可以在类主体中使用来指代类本身:

The name of a class can be used as a class-name even within the member-list of the class specifier itself.

  • For example,

    class link { link* next; };

关于c++ - 为什么会有注入(inject)的类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41704113/

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