static_rtti
static_rtti

Reputation: 56282

Typedef of templated class inside class

I'm wondering why the following code works:

template <class T>
class A {
  public:
  typedef A* Pointer;
  typedef A<T>* OtherPointer;
};

int main()
{
  A<double> a;
  A<double>::Pointer b = &a;
  A<double>::OtherPointer c = &a;
  std::cout << b << " " << c << std::endl;
}

The syntax for OtherPointer looks logical to me. I'm wondering about the one for Pointer. Is the name of the class implicitly the templated type inside the class definition? If so, why does the other syntax work as well?

Upvotes: 2

Views: 87

Answers (1)

Jason R
Jason R

Reputation: 11696

It works because inside the class template A<T>, the type name A is an alias for the fully-described type A<T>. Your template definition above is equivalent to:

template <class T>
class A {
  public:
  typedef A<T>* Pointer;
  typedef A<T>* OtherPointer;
};

As you can see when you write it this way, A<T>::Pointer and A<T>::OtherPointer are typedefs for the same type (which is just A<T> itself). Therefore, your example compiles successfully.

Someone else may be able to quote from the relevant portion of the standard on this. It should be said that I know that this is an area in particular where I've seen bugs in some older compilers in the past, where A is not treated as equivalent to A<T> inside the template definition.

Upvotes: 4

Related Questions