Template parameters and template arguments

Template parameters

Every

template

is parameterized by one or more template parameters, indicated in the parameter-list of the template declaration syntax:

template<parameter-list>declaration(1) template<parameter-list>requiresconstraintdeclaration(2) (since C++20)Each parameter in parameter-list may be:

a non-type template parameter;

a type template parameter;

a template template parameter.

P2841

(Concept and variable-template template-parameters) renamed “non-type template parameter/argument” to “constant template parameter/argument” without changing their meanings. Due to the extensive usage of the “non-type template parameter” and its abbreviation “NTTP”, the current terminologies are preserved. Non-type template parameter

typename(optional)(1) typename(optional)=default(2) type...name(optional)(3) (since C++11)1) A non-type template parameter.

2) A non-type template parameter with a default template argument.

type- one of the following types: a structural type (see below)

name- the name of the non-type template parameter default- the

default template argument

A structural type is one of the following types (optionally cv-qualified, the qualifiers are ignored):

lvalue reference type

(to object or to function);

an

integral type

;

a

pointer type

(to object or to function);

a

pointer to member type

(to member object or to member function);

an

enumeration type

;

std::nullptr_t

;

(since C++11)a

floating-point type

;

a

lambda closure type

whose lambda expression has no capture;

a non-closure

literal class type

with the following properties:

all base classes and non-static data members are public and non-mutable and

the types of all base classes and non-static data members are structural types or (possibly multi-dimensional) array thereof;

(since C++20)

std::meta::info

.

(since C++26)Array and function types may be written in a template declaration, but they are automatically replaced by pointer to object and pointer to function as appropriate.

When the name of a non-type template parameter is used in an expression within the body of the class template, it is an unmodifiable

prvalue

unless its type was an lvalue reference type, or unless its type is a class type(since C++20).

A template parameter of the form classFoo is not an unnamed non-type template parameter of type Foo, even if otherwise classFoo is an

elaborated type specifier

and classFoox; declares x to be of type Foo.

An

identifier

that names a non-type template parameter of class type T denotes a static storage duration object of type constT, called a template parameter object, which is

template-argument-equivalent

to the corresponding template argument after it has been converted to the type of the template parameter. No two template parameter objects are template-argument-equivalent.

structA{friendbooloperator==(constA&,constA&)=default;};template<Aa>voidf(){&a;// OKconstA&ra=a,&rb=a;// Both bound to the same template parameter objectassert(&ra==&rb);// passes}Template parameter objects can also be created by reflection functions such as std::meta::reflect_constant_array.

(since C++26)(since C++20)Type template parameter

type-parameter-keyname(optional)(1) type-parameter-keyname(optional)=default(2) type-parameter-key...name(optional)(3) (since C++11)type-constraintname(optional)(4) (since C++20)type-constraintname(optional)=default(5) (since C++20)type-constraint...name(optional)(6) (since C++20)type-parameter-key- either typename or class. There is no difference between these keywords in a type template parameter declaration type-constraint- either the name of a

concept

or the name of a concept followed by a list of template arguments (in angle brackets). Either way, the concept name may be optionally qualified name- the name of the type template parameter default- the

default template argument

1) A type template parameter without a default.

template<classT>classMy_vector{/* ... */};2) A type template parameter with a default.

template<classT=void>structMy_op_functor{/* ... */};3) A type template

parameter pack

.

template<typename...Ts>classMy_tuple{/* ... */};4) A constrained type template parameter without a default.

template<My_conceptT>classMy_constrained_vector{/* ... */};5) A constrained type template parameter with a default.

template<My_conceptT=void>classMy_constrained_op_functor{/* ... */};6) A constrained type template

parameter pack

.

template<My_concept...Ts>classMy_constrained_tuple{/* ... */};The name of the parameter is optional:

// Declarations of the templates shown above:template<class>classMy_vector;template<class=void>structMy_op_functor;template<typename...>classMy_tuple;In the body of the template declaration, the name of a type parameter is a typedef-name which aliases the type supplied when the template is instantiated.

Each constrained parameter P whose type-constraint is Q designating the concept C introduces a

constraint-expression

E according to the following rules:

if Q is C (without an argument list),

if P is not a parameter pack, E is simply C<P>

otherwise, P is a parameter pack, E is a fold-expression (C<P> && ...)

if Q is C<A1,A2...,AN>, then E is C<P,A1,A2,...AN> or (C<P,A1,A2,...AN> && ...), respectively.

template<typenameT>conceptC1=true;template<typename...Ts>// variadic conceptconceptC2=true;template<typenameT,typenameU>conceptC3=true;template<C1T>structs1;// constraint-expression is C1<T>template<C1...T>structs2;// constraint-expression is (C1<T> && ...)template<C2...T>structs3;// constraint-expression is (C2<T> && ...)template<C3<int>T>structs4;// constraint-expression is C3<T, int>template<C3<int>...T>structs5;// constraint-expression is (C3<T, int> && ...)(since C++20)Template template parameter

template<parameter-list>type-parameter-keyname(optional)(1) template<parameter-list>type-parameter-keyname(optional)=default(2) template<parameter-list>type-parameter-key...name(optional)(3) (since C++11)type-parameter-key- classor typename(since C++17)1) A template template parameter with an optional name.

2) A template template parameter with an optional name and a default.

3) A template template

parameter pack

with an optional name.

In the body of the template declaration, the name of this parameter is a template-name (and needs arguments to be instantiated).

template<typenameT>classmy_array{};// two type template parameters and one template template parameter:template<typenameK,typenameV,template<typename>typenameC=my_array>classMap{C<K>key;C<V>value;};Name resolution for template parameters

The name of a template parameter is not allowed to be redeclared within its scope (including nested scopes). A template parameter is not allowed to have the same name as the template name.

template<classT,intN>classY{intT;// error: template parameter redeclaredvoidf(){charT;// error: template parameter redeclared}};template<classX>classX;// error: template parameter redeclaredIn the definition of a member of a class template that appears outside of the class template definition, the name of a member of the class template hides the name of a template parameter of any enclosing class templates, but not a template parameter of the member if the member is a class or function template.

template<classT>structA{structB{};typedefvoidC;voidf();template<classU>voidg(U);};template<classB>voidA<B>::f(){Bb;// A's B, not the template parameter}template<classB>template<classC>voidA<B>::g(C){Bb;// A's B, not the template parameterCc;// the template parameter C, not A's C}In the definition of a member of a class template that appears outside of the namespace containing the class template definition, the name of a template parameter hides the name of a member of this namespace.

namespaceN{classC{};template<classT>classB{voidf(T);};}template<classC>voidN::B<C>::f(C){Cb;// C is the template parameter, not N::C}In the definition of a class template or in the definition of a member of such a template that appears outside of the template definition, for each non-

dependent

base class, if the name of the base class or the name of a member of the base class is the same as the name of a template parameter, the base class name or member name hides the template parameter name.

structA{structB{};intC;intY;};template<classB,classC>structX:A{Bb;// A's BCb;// error: A's C isn't a type name};Template arguments

In order for a template to be instantiated, every template parameter (type, non-type, or template) must be replaced by a corresponding template argument. For

class templates

, the arguments are either explicitly provided,

deduced from the initializer

, (since C++17) or defaulted. For

function templates

, the arguments are explicitly provided,

deduced from the context

, or defaulted.

If an argument can be interpreted as both a

type-id

and an expression, it is always interpreted as a type-id, even if the corresponding template parameter is non-type:

template<classT>voidf();// #1template<intI>voidf();// #2voidg(){f<int()>();// "int()" is both a type and an expression,// calls #1 because it is interpreted as a type}Non-type template arguments

Given the type of the

non-type template parameter declaration

as T and the template argument provided for the parameter as E.

The invented declaration Tx=E; must satisfy the semantic constraints for the definition of a

constexpr variable

with

static storage duration

.

(since C++26)If T contains a

placeholder type

, or is a

placeholder for a deduced class type

, the type of the template parameter is the type deduced for the variable x in the invented declaration Tx=E;.

If a deduced parameter type is not a

structural type

, the program is ill-formed.

For non-type template parameter packs whose type uses a placeholder type, the type is independently deduced for each template argument and need not match.

(since C++17)template<auton>structB{/* ... */};B<5>b1;// OK: non-type template parameter type is intB<'a'>b2;// OK: non-type template parameter type is charB<2.5>b3;// error (until C++20): non-type template parameter type cannot be double// C++20 deduced class type placeholder, class template arguments are deduced at the// call sitetemplate<std::arrayarr>voidf();f<std::array<double,8>{}>();template<auto...>structC{};C<'C',0,2L,nullptr>x;// OKThe value of a non-type template parameter P of (possibly deduced)(since C++17) type T is determined from its template argument A as follows:

If A is a

converted constant expression

of type T, the value of P is A (as converted).

Otherwise, the program is ill-formed.

(until C++11)If A is an expression:

If A is a

converted constant expression

of type T, the value of P is A (as converted).

Otherwise, the program is ill-formed.

Otherwise (A is a braced-enclosed initializer list), a temporary variable constexprTv=A; is introduced. The value of P is that of v.

The

lifetime

of v ends immediately after initializing it.

(since C++11)
(until C++20)If T is not a class type and A is an expression:

If A is a

converted constant expression

of type T, the value of P is A (as converted).

Otherwise, the program is ill-formed.

Otherwise (T is a class type or A is a braced-enclosed initializer list), a temporary variable constexprTv=A; is introduced.

If T is a class type, a

template parameter object

exists (which is also denoted by P). P is copy-initialized from an unspecified candidate initializer that is

template-argument-equivalent

to v.

The

lifetime

of v ends immediately after initializing it and P.

If the initialization of P satisfies any of the following conditions, the program is ill-formed:

The initialization would be ill-formed.

The

full-expression

of an invented declarator-initializer sequence for the initialization would not be a constant expression when interpreted as a

manifestly constant-evaluated expression

.

The initialization would cause P to not be

template-argument-equivalent

to v.

Otherwise, the value of P is that of v.

(since C++20)template<inti>structC{/* ... */};C<{42}>c1;// OKtemplate<auton>structB{/* ... */};structJ1{J1*self=this;};B<J1{}>j1;// error: initialization of the template parameter object// is not a constant expressionstructJ2{J2*self=this;constexprJ2(){}constexprJ2(constJ2&){}};B<J2{}>j2;// error: the template parameter object is not// template-argument-equivalent to introduced temporaryThe following limitations apply when instantiating templates that have non-type template parameters:

For integral and arithmetic types, the template argument provided during instantiation must be a

converted constant expression

of the template parameter's type (so certain implicit conversion applies).

For pointers to objects, the template arguments have to designate the address of a complete object with static

storage duration

and a

linkage

(either internal or external), or a constant expression that evaluates to the appropriate null pointer or

std::nullptr_t

(since C++11) value.

For pointers to functions, the valid arguments are pointers to functions with linkage (or constant expressions that evaluate to null pointer values).

For lvalue reference parameters, the argument provided at instantiation cannot be a temporary, an unnamed lvalue, or a named lvalue with no linkage (in other words, the argument must have linkage).

For pointers to members, the argument has to be a pointer to member expressed as &Class::Member or a constant expression that evaluates to null pointer or

std::nullptr_t

(since C++11) value.

In particular, this implies that string literals, addresses of array elements, and addresses of non-static members cannot be used as template arguments to instantiate templates whose corresponding non-type template parameters are pointers to objects.

(until C++17)Non-type template parameters of reference or pointer type and non-static data members of reference or pointer type in a non-type template parameter of class type and its subobjects(since C++20) cannot refer to/be the address of

a temporary object (including one created during

reference initialization

);

a

string literal

;

the result of

typeid

;

the predefined variable __func__;

or a subobject (including non-static class member, base subobject, or array element) of one of the above(since C++20).

(since C++17)template<constint*pci>structX{};intai[10];X<ai>xi;// OK: array to pointer conversion and cv-qualification conversionstructY{};template<constY&b>structZ{};Yy;Z<y>z;// OK: no conversiontemplate<int(&pa)[5]>structW{};intb[5];W<b>w;// OK: no conversionvoidf(char);voidf(int);template<void(*pf)(int)>structA{};A<&f>a;// OK: overload resolution selects f(int)template<classT,constchar*p>classX{};X<int,"Studebaker">x1;// error: string literal as template-argumenttemplate<int*p>classX{};inta[10];structS{intm;staticints;}s;X<&a[2]>x3;// error (until C++20): address of array elementX<&s.m>x4;// error (until C++20): address of non-static memberX<&s.s>x5;// OK: address of static memberX<&S::s>x6;// OK: address of static membertemplate<constint&CRI>structB{};B<1>b2;// error: temporary would be required for template argumentintc=1;B<c>b1;// OKType template arguments

A template argument for a type template parameter must be a

type-id

, which may name an incomplete type:

template<typenameT>classX{};// class templatestructA;// incomplete typetypedefstruct{}B;// type alias to an unnamed typeintmain(){X<A>x1;// OK: 'A' names a typeX<A*>x2;// OK: 'A*' names a typeX<B>x3;// OK: 'B' names a type}Template template arguments

A template argument for a template template parameter must be an

id-expression

which names a class template or a template alias.

When the argument is a class template, only the primary template is considered when matching the parameter. The partial specializations, if any, are only considered when a specialization based on this template template parameter happens to be instantiated.

template<typenameT>// primary templateclassA{intx;};template<typenameT>// partial specializationclassA<T*>{longx;};// class template with a template template parameter Vtemplate<template<typename>classV>classC{V<int>y;// uses the primary templateV<int*>z;// uses the partial specialization};C<A>c;// c.y.x has type int, c.z.x has type longTo match a template template argument A to a template template parameter P, P must be at least as specialized as A (see below). If P's parameter list includes a

parameter pack

, zero or more template parameters (or parameter packs) from A's template parameter list are matched by it.(since C++11)

Formally, a template template-parameter P is at least as specialized as a template template argument A if, given the following rewrite to two function templates, the function template corresponding to P is at least as specialized as the function template corresponding to A according to the partial ordering rules for

function templates

. Given an invented class template X with the template parameter list of A (including default arguments):

Each of the two function templates has the same template parameters, respectively, as P or A.

Each function template has a single function parameter whose type is a specialization of X with template arguments corresponding to the template parameters from the respective function template where, for each template parameter PP in the template parameter list of the function template, a corresponding template argument AA is formed. If PP declares a parameter pack, then AA is the pack expansion PP...; otherwise,(since C++11)AA is the id-expression PP.

If the rewrite produces an invalid type, then P is not at least as specialized as A.

template<typenameT>structeval;// primary templatetemplate<template<typename,typename...>classTT,typenameT1,typename...Rest>structeval<TT<T1,Rest...>>{};// partial specialization of evaltemplate<typenameT1>structA;template<typenameT1,typenameT2>structB;template<intN>structC;template<typenameT1,intN>structD;template<typenameT1,typenameT2,intN=17>structE;eval<A<int>>eA;// OK: matches partial specialization of evaleval<B<int,float>>eB;// OK: matches partial specialization of evaleval<C<17>>eC;// error: C does not match TT in partial specialization// because TT's first parameter is a// type template parameter, while 17 does not name a typeeval<D<int,17>>eD;// error: D does not match TT in partial specialization// because TT's second parameter is a// type parameter pack, while 17 does not name a typeeval<E<int,float>>eE;// error: E does not match TT in partial specialization// because E's third (default) parameter is a non-typeBefore the adoption of

P0522R0

, each of the template parameters of A must match corresponding template parameters of P exactly. This hinders many reasonable template argument from being accepted.

Although it was pointed out very early (

CWG#150

), by the time it was resolved, the changes were applied to the C++17 working paper and the resolution became a de facto C++17 feature. Many compilers disable it by default:

GCC

disables it in all language modes prior to C++17 by default, it can only be enabled by setting a compiler flag in these modes.

Clang

disables it in all language modes by default, it can only be enabled by setting a compiler flag.

Microsoft Visual Studio

treats it as a normal C++17 feature and only enables it in C++17 and later language modes (i.e. no support in C++14 language mode, which is the default mode).

template<classT>classA{/* ... */};template<classT,classU=T>classB{/* ... */};template<class...Types>classC{/* ... */};template<template<class>classP>classX{/* ... */};X<A>xa;// OKX<B>xb;// OK after P0522R0// Error earlier: not an exact matchX<C>xc;// OK after P0522R0// Error earlier: not an exact matchtemplate<template<class...>classQ>classY{/* ... */};Y<A>ya;// OKY<B>yb;// OKY<C>yc;// OKtemplate<auton>classD{/* ... */};// note: C++17template<template<int>classR>classZ{/* ... */};Z<D>zd;// OK after P0522R0: the template parameter// is more specialized than the template argumenttemplate<int>structSI{/* ... */};template<template<auto>class>voidFA();// note: C++17FA<SI>();// ErrorDefault template arguments

Default template arguments are specified in the parameter lists after the = sign. Defaults can be specified for any kind of template parameter (type, non-type, or template), but not to parameter packs(since C++11).

If the default is specified for a template parameter of a primary class template, primary variable template,(since C++14) or alias template, each subsequent template parameter must have a default argument, except the very last one may be a template parameter pack(since C++11). In a function template, there are no restrictions on the parameters that follow a default, and a parameter pack may be followed by more type parameters only if they have defaults or can be deduced from the function arguments(since C++11).

Default parameters are not allowed

in the out-of-class definition of a member of a

class template

(they have to be provided in the declaration inside the class body). Note that

member templates

of non-template classes can use default parameters in their out-of-class definitions (see

GCC bug 53856

)

in

friend class template

declarations

On a friend function template declaration, default template arguments are allowed only if the declaration is a definition, and no other declarations of this function appear in this translation unit.

(since C++11)Default template arguments that appear in the declarations are merged similarly to default function arguments:

template<typenameT1,typenameT2=int>classA;template<typenameT1=int,typenameT2>classA;// the above is the same as the following:template<typenameT1=int,typenameT2=int>classA;But the same parameter cannot be given default arguments twice in the same scope:

template<typenameT=int>classX;template<typenameT=int>classX{};// errorWhen parsing a default template argument for a non-type template parameter, the first non-nested > is taken as the end of the template parameter list rather than a greater-than operator:

template<inti=3>4>// syntax errorclassX{/* ... */};template<inti=(3>4)>// OKclassY{/* ... */};The template parameter lists of template template parameters can have their own default arguments, which are only in effect where the template template parameter itself is in scope:

// class template, with a type template parameter with a defaulttemplate<typenameT=float>structB{};// template template parameter T has a parameter list, which// consists of one type template parameter with a defaulttemplate<template<typename=float>typenameT>structA{voidf();voidg();};// out-of-body member function template definitionstemplate<template<typenameTT>classT>voidA<T>::f(){T<>t;// error: TT has no default in scope}template<template<typenameTT=char>classT>voidA<T>::g(){T<>t;// OK: t is T<char>}

Member access

for the names used in a default template parameter is checked at the declaration, not at the point of use:

classB{};template<typenameT>classC{protected:typedefTTT;};template<typenameU,typenameV=typenameU::TT>classD:publicU{};D<C<B>>*d;// error: C::TT is protectedThe default template argument is implicitly instantiated when the value of that default argument is needed, except if the template is used to name a function:

template<typenameT,typenameU=int>structS{};S<bool>*p;// The default argument for U is instantiated at this point// the type of p is S<bool, int>*(since C++14)Template argument equivalence

Template argument equivalence is used to determine whether two

template identifiers

are same.

Two values are template-argument-equivalent if they are of the same type and any of the following conditions is satisfied:

They are of integral or enumeration type and their values are the same.

They are of pointer type and they have the same pointer value.

They are of pointer-to-member type and they refer to the same class member or are both the null member pointer value.

They are of lvalue reference type and they refer to the same object or function.

They are of type

std::nullptr_t

.

(since C++11)They are of floating-point type and their values are identical.

They are of array type (in which case the arrays must be member objects of some class/union)(until C++26) and their corresponding elements are template-argument-equivalent.

They are of union type and either they both have no active member or they have the same active member and their active members are template-argument-equivalent.

They are of a lambda closure type.

They are of non-union class type and their corresponding direct subobjects and reference members are template-argument-equivalent.

(since C++20)They are of type

std::meta::info

and their values

compare equal

.

(since C++26)Notes

In template parameters, type constraints could be used for both type and non-type parameters, depending on whether auto is present.

template<typename>conceptC=true;template<C,// type parameter Cauto// non-type parameter>structS{};S<int,0>s;(since C++20)Feature-test macro ValueStdFeature

__cpp_nontype_template_parameter_auto

201606L

(C++17)Declaring

non-type template parameters

with auto

__cpp_template_template_args

201611L

(c++17)
(DR)Matching of

template template-arguments

__cpp_nontype_template_args

201411L

(C++17)Allow constant evaluation for all

non-type template arguments

201911L

(C++20)Class types and floating-point types in

non-type template parameters

__cpp_template_parameters

202502L

(C++26)Concept and

variable-template template-parameters

Examples

Run this code

#include<array>#include<iostream>#include<numeric>// simple non-type template parametertemplate<intN>structS{inta[N];};template<constchar*>structS2{};// complicated non-type exampletemplate<charc,// integral typeint(&ra)[5],// lvalue reference to object (of array type)int(*pf)(int),// pointer to functionint(S<10>::*a)[10]// pointer to member object (of type int[10])>structComplicated{// calls the function selected at compile time// and stores the result in the array selected at compile timevoidfoo(charbase){ra[4]=pf(c-base);}};// S2<"fail"> s2; // error: string literal cannot be usedcharokay[]="okay";// static object with linkage// S2<&okay[0]> s3; // error: array element has no linkageS2<okay>s4;// worksinta[5];intf(intn){returnn;}// C++20: NTTP can be a literal class typetemplate<std::arrayarr>constexprautosum(){returnstd::accumulate(arr.cbegin(),arr.cend(),0);}// C++20: class template arguments are deduced at the call sitestatic_assert(sum<std::array<double,8>{3,1,4,1,5,9,2,6}>()==31.0);// C++20: NTTP argument deduction and CTADstatic_assert(sum<std::array{2,7,1,8,2,8}>()==28);intmain(){S<10>s;// s.a is an array of 10 ints.a[9]=4;Complicated<'2',a,f,&S<10>::a>c;c.foo('0');std::cout<<s.a[9]<<a[4]<<'\n';}Output:

42 Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior

CWG 150

(

P0522R0

) C++98 template-template arguments had to match parameter
lists of template-template parameters exactly more specialized
also allowed

CWG 184

C++98 whether the template parameters of template template
parameters are allowed to have default arguments is unspecified specification added

CWG 354

C++98 null pointer values could not be non-type template arguments allowed

CWG 1398

C++11 non-type template arguments could not have type std::nullptr_tallowed

CWG 1570

C++98 non-type template arguments could designate addresses of subobjects not allowed

CWG 1922

C++98 it was unclear whether a class template whose name is an
injected-class-name can use the default arguments in prior declarations allowed

CWG 2032

C++14 for variable templates, there was no restriction on the template
parameters after a template parameter with a default argument apply the same restriction
as on class templates
and alias templates

CWG 2542

C++20 it was unclear whether the closure type is structural it is not structural

CWG 2845

C++20 the closure type was not structural it is structural
if capture-less

P2308R1

C++11
C++20 1. list-initialization was not allowed for
non-type template arguments (C++11)
2. it was unclear how non-type template
parameters of class types are initialized (C++20) 1. allowed
2. made clear