views:

90

answers:

3

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
+5  A: 

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

sinec
And because the . operator is the _member_ access operator.
anon
@Neil Butterworth: Thanks:)
sinec
A: 

I can't tell why it is not allowed exactly. t.value_type, *value_type* is member variable of the instance t, if it's a user-defined type, it may be confusing.

Cliffwolf
A: 

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>.
Joe Gauterin
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.
Space_C0wb0y