简体   繁体   English

为什么对嵌套类型的访问会影响C ++中的成员解析?

[英]Why does access to nested types affect member resolution in C++?

Assume I have a simple structure... 假设我有一个简单的结构......

struct A {
    std::vector<uint32_t> v;
};

And I want to find the size of the vector element type... 我想找到矢量元素类型的大小......

sizeof(A::v);                        // legal
sizeof(decltype(A().v)::value_type); // legal
sizeof(A::v::value_type)             // illegal 

Error message... 错误信息...

example.cpp:18:44: error: no member named 'v' in 'A' example.cpp:18:44:错误:'A'中没有名为'v'的成员

Why does the third version fail? 为什么第三个版本失败了? I don't understand how adding another layer of scope resolution causes the more broad scope resolution to fail. 我不明白如何添加另一层范围解析会导致更广泛的范围解析失败。 In fact, the second example seems equivalent to the failing example, but obviously the compiler disagrees. 事实上,第二个例子似乎等同于失败的例子,但显然编译器不同意。

This is a what-if/language question. 这是假设/语言问题。 I am not trying to solve a particular problem with vector sizes but rahter understand this oddity of the language. 我并不是试图解决矢量大小的特定问题,而是了解这种语言的奇怪之处。

Update 更新

Here is another example from an answer below that seems to further my confusion... 下面的答案中的另一个例子似乎进一步让我感到困惑......

sizeof(decltype(A::v)::value_type);  // legal  

How is decltype(A::v)::value_type different from A::v::value_type in this context? 在这种情况下, decltype(A::v)::value_typeA::v::value_type有何不同?

I don't think you can get a typename from a variable using the :: token. 我不认为你可以使用:: token从变量中获取一个typename。 Ignore sizeof and ignore A::v. 忽略sizeof并忽略A :: v。 The following doesn't work: 以下不起作用:

A a; // A is some type with a public typedef for value_type in its declaration
A::value_type b; // ok
a::value_type c; // error

GCC 4.7.1 gives me this error: GCC 4.7.1给了我这个错误:

x.cpp:9:1: error: 'a' does not name a type

sizeof makes this confusing only because it is a compile time construct that accepts both types and variables as its parameter. sizeof使得这一点令人困惑,因为它是一个编译时构造,它接受类型和变量作为参数。

Correct me if I'm wrong but doesn't the last one fail because you are accessing an instance in the last one whereas in the second one you get the class name from the decltype(). 纠正我,如果我错了,但最后一个失败是因为你正在访问最后一个实例,而在第二个你从decltype()获得类名。 If you wrap the third one in a decltype it works 如果你将第三个包装在一个decltype中就可以了

sizeof(decltype(A::v)::value_type); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM