Il-seob Bae Il-seob Bae - 1 month ago 7
C++ Question

"typename qualified-id" referring to a type in a non-type parameter-declaration


14.1 [temp.param], paragraph 2



...
typename
followed by an unqualified-id names a template type parameter.
typename
followed by a qualified-id denotes the type in a non-type parameter-declaration
...


I'm a bit confused about the meaning of the bold text. Specifically,
typename
can occur in two different contexts (type-specifier or template-parameter), but which one does this refer to?


  • For the former case, I considered:

    struct A {
    struct X { };
    int X;
    };
    struct B {
    struct X { };
    };
    template<class T> void f(T t) {
    typename T::X x; // T can be A or B
    }


    However, neither
    A::X
    nor
    B::X
    is a non-type parameter-declaration (they are member-declarations).

  • For the latter case, I'm not sure why that's necessary. Why not directly write down its type with qualified-id? Is parameterization necessary?


hvd hvd
Answer

This is about

struct S { typedef int X; };
template <typename T, typename T::X> void f() { }
int main() { f<S, 1>(); }

Here, typename T means T is a named template type parameter, but typename T::X is the type of an unnamed non-type template parameter.

type-parameter is the syntax used for template type parameters, parameter-declaration is the syntax used for template non-type parameters.

typename T cannot be parsed as a typename-specifier in a parameter-declaration, as it lacks the nested-name-specifier, so it must be a type-parameter.

typename T::X cannot be parsed as a type-parameter, as it only allows a single identifier after the typename keyword, so it must be a parameter-declaration.

I think there's no ambiguity, but the text clarifies how differently these two template-parameters are parsed.