Template Body Parsing

From RAD Studio
Jump to: navigation, search

Go Up to C++ Specifics Index


Earlier versions of the compiler didn't check the syntax of a template body unless the template was instantiated. A template body is now parsed immediately when seen like every other declaration.

template <class T> class X : T
{
  Int  j;  // Error: Type name expected in template X<T>
};

Let's assume that Int hasn't yet been defined. This means that Int must be a member of the template argument T. But it also might just be a typing error and should be int instead of Int. Because the compiler can't guess the right meaning it issues an error message.

If you want to access types defined by a template argument you should use a typedef to make your intention clear to the compiler:

template <class T> class X : T
{
  typedef  typename T::Int  Int;
  Int  j;
};

You cannot just write

   typedef   T::Int;

as in earlier versions of the compiler. Not giving the typedef name was acceptable, but this now causes an error message.

All other templates mentioned inside the template body are declared or defined at that point. Therefore, the following example is ill-formed and will not compile:

template <class T> class  X
{
  void f(NotYetDefindedTemplate<T> x);
};

All template definitions must end with a semicolon. Earlier versions of the compiler did not complain if the semicolon was missing.

See Also