开发者

Accessing typedef from the instance

开发者 https://www.devze.com 2023-01-03 18:13 出处:网络
As in stl containers, why can\'t we access a typedef inside the class from 开发者_JAVA百科the class instance? Is there a particular insight into this?

As in stl containers, why can't we access a typedef inside the class from 开发者_JAVA百科the class instance? Is there a particular insight into this?


When value_type was a template parameter it could help making more general code if there wasn't the need to specify the template parameters as in vector::value_type

Example:

class T {
public:
    typedef int value_type;
    value_type i;
};

T t;
T::value_type i; // ok
t.value_type i;  // won't work


The answer is use decltype to get the class first. E.g.,

decltype(t)::value_type

Requires C++11.

Reference: https://stackoverflow.com/a/13936644/577704


Because the typedef is just a synonym for another type. It is not an object (class's member).

And as @Neil Butterworth mentioned: "Because the . operator is the member access operator."


There's no good reason for using a different operator for scope resolution (::) than for member access (.) as it's never ambiguous. It's an annoyance, but it's just the way the language is.


Some languages do it differently though...

  • C# uses . instead of ::, but you still need to use the class name when accessing nested types and static members.
  • D uses ., and <instance>.<static nested type> is equivilent to <type>.<static nested type>.
0

精彩评论

暂无评论...
验证码 换一张
取 消