Accessing typedef from the instance

余生颓废 提交于 2021-02-04 16:57:28

问题


As in stl containers, why can't we access a typedef inside the class from 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

回答1:


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




回答2:


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."




回答3:


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>.


来源:https://stackoverflow.com/questions/3068562/accessing-typedef-from-the-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!