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

3 Answers 3

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

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

1
  • And because the . operator is the member access operator.
    – anon
    Jun 18, 2010 at 9:45
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>.
1
  • 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. Jun 18, 2010 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.