Search code examples
c++classoopconstantstypename

Should typename be before or after const in C++?


Should I write:

template<class T> class Foo {
    typename const T* x;
};

or:

template<class T> class Foo {
    const typename T* x;
};

Solution

  • typename is not used like this, so both cases are invalid and should produce a compilation error, like this:

    main.cpp:4:20: error: expected a qualified name after 'typename'
        const typename T* x;
                       ^
    

    Here you would need something like T::myType to go on.

    Or even this, which is worse:

    main.cpp:4:14: error: expected a qualified name after 'typename'
        typename const T* x;
                 ^
    main.cpp:4:14: error: expected member name or ';' after declaration specifiers
    

    Relevant example in expected a qualified name after 'typename'.


    The keyword typename was introduced to specify that the identifier that follows is a type

    Read more in: Officially, what is typename for?