18

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
piotr
  • 5,657
  • 1
  • 35
  • 60

3 Answers3

14

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

Community
  • 1
  • 1
Ivan Xiao
  • 1,919
  • 3
  • 19
  • 30
7

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

sinek
  • 2,458
  • 3
  • 33
  • 55
1

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>.
JoeG
  • 12,994
  • 1
  • 38
  • 63
  • 1
    It's not just the different operator. `::` is called on the type, whereas `.` is called on the instance. But still, I too can see no good reason for not using the same. – Björn Pollex Jun 18 '10 at 10:04