Typename is a C++ keyword. It can appear in two places:

  1. In the formal parameter list of a template.

    template <typename T> class foo { ... };

    There it is indistinguishable from the keyword class. Certain non-standard-comforming compilers distinguish between the two words to forbid class parameters being specialized with builtin types.

    This use of typename should be avoided if at all possible.

  2. In a class-scope typedef declaration, to give the compiler a hint as to whether an as-yet undeclared identifier is a type:

    typedef typename foo foo_alias;

    This use is somewhat more meaningful. If you have a template taking a class as a parameter, and you want to use typedef-names declared in the parameter class, you need to specity typename in order for your code to compile:

    struct Foo
    {
     typedef unsigned short size_type;
    };

    struct Bar
    {
     typedef unsigned long size_type;
    };

    template <class T>
    struct Baz
    {
     // typedef T::size_type size_type; // error - undeclared identifier
     typedef typename T::size_type size_type; // OK
     static const size_type size_size = sizeof (size_type);
    };

    typedef Baz<Foo> foo_baz;
    typedef Baz<Bar> bar_baz;

    //
    // foo_baz::size_type is "unsigned short"
    // bar_baz::size_type is "unsigned long"
    //

Log in or register to write something here or to contact authors.