gpt4 book ai didi

C++类名注入(inject)

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:41 26 4
gpt4 key购买 nike

根据标准[class]/2:

… The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name.…

此外,[basic.scope.pdecl]/9:

The point of declaration for an injected-class-name (Clause 9) is immediately following the opening brace of the class definition.

最后,[basic.lookup.classref]/3 及其示例:

If the unqualified-id is ~ type-name, the type-name is looked up …

struct A { };
struct B {
struct A { };
void f(::A* a);
};
void B::f(::A* a) {
a-> ~ A(); // OK: lookup in *a finds the injected-class-name
}

到目前为止,我们可以收集到:

  1. 在类A的范围内,存在一个名字A。
  2. 该名称在类 A 的定义大括号的开头声明。
  3. 这个名字命名了一个类型。

如果上面是正确的,那么为什么下面的代码编译失败(在MSVC2015中):

struct inj
{};

typedef struct inj::inj inj2;

错误信息

Error C2039 '{ctor}': is not a member of 'inj'

似乎与标准不一致:

Note: For example, the constructor is not an acceptable lookup result in an elaborated-type-specifier so the constructor would not be used in place of the injected-class-name. —end note

最佳答案

由于以下代码在其他编译器中编译和运行正确,因此它是 MSVC2015 中的一个错误。

#include <boost/type_index.hpp>
#include <iostream>

struct inj
{
int g;
};

typedef struct inj::inj inj2;

int main()
{

inj2 ii;
std::cout << boost::typeindex::type_id_with_cvr<decltype(ii)>().pretty_name() << '\n';
}

更新:Reported as bug .

关于C++类名注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31769853/

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