Friday, June 24, 2005

Scope of typedefs in a class in C++

I found this in the latest C++ draft specification

Type names obey exactly the same scope rules as other names.In particular, type names defined within a class definition cannot be used outside their class without qualification.

Example:


class X {
public :
typedef int I;
class Y { / . . . / };
I a;
};

I b; // error
Y c; // error
X::Y d; // OK
X::I e; // OK

2 comments:

Kaushik said...

Most STL classes like vector and list use this facility to define their local typedefs.

For instance, all the collection classes define their own versions of iterator, const_iterator, value_type etc., within the class definition.

-K

Balbir Singh said...

Thanks for that information Kaushik. I see it now. There is an implementation of typesafe c++ enums that uses similar concepts. You can find it artima weblogs.

Dynamic programming for the binomial coefficient

More fun things, this time with some visualisation of what happens when memoisation is used and what happens when we don't. I don'...