Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

typename — type parameters and type-name disambiguation

The typename keyword declares a template type parameter or indicates that a qualified name denotes a type. These roles are distinct: class can replace typename when declaring a type parameter, but not when disambiguating a name such as T::value_type.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

template<typename T> struct Box;
template<typename... Ts> struct Pack;
typename T::value_type value{};
typename T::template rebind<int>::type other{};

typename has two main roles. In template<typename T>, it declares a type parameter; class is equivalent here and does not restrict the argument to a class type. The form template<typename... Ts> declares a type parameter pack.

Before a qualified name, such as typename T::value_type, it specifies interpretation as a type. In the example's template function body, T::value_type depends on T and has not already been established as a type, so typename is required. The keyword neither creates a type nor turns a data member into one: lookup must still find an appropriate type.

Not every dependent type name requires this prefix. In C++23, it can be omitted in type-only contexts, such as using Value = T::value_type;, and when the name is already recognized as a type. Do not add typename before a bare T when declaring a variable; this specifier form requires a qualified name. In typename T::template rebind<int>::type, template separately indicates that dependent rebind is a template; it does not replace typename.

The example uses both main roles and should print 42 followed by a newline. This entry targets C++23; the supplied site hosts an evolving draft rather than a frozen C++23 text. The compiler flag does not attest to a production environment or to execution of the example.

Examples

#include <iostream>

struct Data {
    using value_type = int;
};

template<typename T>
void print_value() {
    typename T::value_type value{42};
    std::cout << value << '\n';
}

int main() {
    print_value<Data>();
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources