MFC Programmer's SourceBook : Thinking in C++
Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

The typename keyword

[[ Adapted; rewrite and exemplify ]]

If a name in a template can refer to a type or something other than a type, then the compiler will assume that name refers to something other than a type.

The typename keyword tells the compiler to interpret a particular name as a type. It must be used for a name that:

  1. Is a qualified name, one that is nested within another type.
  2. Depends on a template argument; somehow, a template argument is involved in the name, and this argument is what causes the ambiguity that results in the compiler assuming that the name refers to something other than a type.
Because the default behavior of the compiler is to assume that a name that fits the above two points is not a type, you must use typename even in places where you think that the compiler ought to be able to figure out the right way to interpret the name on its own. In short, if your type is a qualified name that involves a template argument, you must use typename.

Typedefing a typename

The typename keyword does not automatically create a typedef. A line which reads:

typename Seq::iterator It;

causes a variable to be declared of type Seq::iterator. If you mean to make a typedef, you must say:

typedef typename Seq::iterator It;

Contents | Prev | Next


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru