Files
2025-10-25 03:02:53 +03:00

108 KiB
Raw Permalink Blame History

[temp.decls]

13 Templates [temp]

13.7 Template declarations [temp.decls]

13.7.1 General [temp.decls.general]

1

#

The template parameters of a template are specified in the angle bracket enclosed list that immediately follows the keyword template.

2

#

A primary template declaration is one in which the name of the template is not followed by a template-argument-list.

The template argument list of a primary template is the template argument list of its template-head ([temp.arg]).

A template declaration in which the name of the template is followed by a template-argument-list is a partial specialization ([temp.spec.partial]) of the template named in the declaration, which shall be a class or variable template.

3

#

For purposes of name lookup and instantiation, default arguments,type-constraints,requires-clauses ([temp.pre]), andnoexcept-specifiers of function templates and of member functions of class templates are considered definitions; each default argument,type-constraint,requires-clause, ornoexcept-specifier is a separate definition which is unrelated to the templated function definition or to any other default arguments,type-constraints,requires-clauses, ornoexcept-specifiers.

For the purpose of instantiation, the substatements of aconstexpr if statement are considered definitions.

For the purpose of name lookup and instantiation, the compound-statement of an expansion-statement is considered a template definition.

4

#

Because an alias-declaration cannot declare atemplate-id, it is not possible to partially or explicitly specialize an alias template.

13.7.2 Class templates [temp.class]

13.7.2.1 General [temp.class.general]

1

#

Aclass template defines the layout and operations for an unbounded set of related types.

2

#

[Example 1:

It is possible for a single class templateList to provide an unbounded set of class definitions: one class List for every type T, each describing a linked list of elements of type T.

Similarly, a class template Array describing a contiguous, dynamic array can be defined like this:template class Array { T* v; int sz;public:explicit Array(int); T& operator; T& elem(int i) { return v[i]; }};

The prefix template specifies that a template is being declared and that atype-name T can be used in the declaration.

In other words,Array is a parameterized type withT as its parameter.

— end example]

3

#

[Note 1:

When a member of a class template is defined outside of the class template definition, the member definition is defined as a template definition with thetemplate-head equivalent to that of the class template.

The names of the template parameters used in the definition of the member can differ from the template parameter names used in the class template definition.

The class template name in the member definition is followed by the template argument list of the template-head ([temp.arg]).

[Example 2: template<class T1, class T2> struct A {void f1(); void f2();};

template<class T2, class T1> void A<T2,T1>::f1() { } // OKtemplate<class T2, class T1> void A<T1,T2>::f2() { } // error

template<class ... Types> struct B {void f3(); void f4();};

template<class ... Types> void B<Types ...>::f3() { } // OKtemplate<class ... Types> void B::f4() { } // error

template concept C = true;template concept D = true;

template struct S {void f(); void g(); void h(); template struct Inner;};

template void S::f() { } // OK, template-heads matchtemplate void S::g() { } // error: no matching declaration for Stemplate requires C // ill-formed, no diagnostic required: template-heads arevoid S::h() { } // functionally equivalent but not equivalenttemplate templatestruct S::Inner { }; // OK — end example]

— end note]

4

#

In a partial specialization, explicit specialization or explicit instantiation of a class template, the class-key shall agree in kind with the original class template declaration ([dcl.type.elab]).

13.7.2.2 Member functions of class templates [temp.mem.func]

1

#

A member function of a class template may be defined outside of the class template definition in which it is declared.

[Example 1: template class Array { T* v; int sz;public:explicit Array(int); T& operator; T& elem(int i) { return v[i]; }};

declares three member functions of a class template.

The subscript function can be defined like this:template T& Array::operator[](int i) {if (i<0 || sz<=i) error("Array: range error"); return v[i];}

A constrained member function can be defined out of line:template concept C = requires {typename T::type;};

template struct S {void f() requires C; void g() requires C;};

templatevoid S::f() requires C { } // OKtemplatevoid S::g() { } // error: no matching function in S

— end example]

2

#

Thetemplate-arguments for a member function of a class template are determined by thetemplate-arguments of the type of the object for which the member function is called.

[Example 2:

Thetemplate-argument forArray::operator[] will be determined by theArray to which the subscripting operation is applied.

Array v1(20); Array v2(30);

v1[3] = 7; // Array::operator[] v2[3] = dcomplex(7,8); // Array::operator[] — end example]

13.7.2.3 Deduction guides [temp.deduct.guide]

1

#

Deduction guides are used when a template-name or splice-type-specifier appears as a type specifier for a deduced class type ([dcl.type.class.deduct]).

Deduction guides are not found by name lookup.

Instead, when performing class template argument deduction ([over.match.class.deduct]), all reachable deduction guides declared for the class template are considered.

deduction-guide:
explicit-specifieropt template-name ( parameter-declaration-clause ) -> simple-template-id requires-clauseopt ;

2

#

[Example 1: template<class T, class D = int>struct S { T data;};template S(U) -> S;

struct A {using type = short; operator type();}; S x{A()}; // x is of type S<short, int> — end example]

3

#

The same restrictions apply to the parameter-declaration-clause of a deduction guide as in a function declaration ([dcl.fct]), except that a generic parameter type placeholder ([dcl.spec.auto]) shall not appear in the parameter-declaration-clause of a deduction guide.

The simple-template-id shall name a class template specialization.

The template-name shall be the same identifier as the template-name of the simple-template-id.

A deduction-guide shall inhabit the scope to which the corresponding class template belongs and, for a member class template, have the same access.

Two deduction guide declarations for the same class template shall not have equivalent parameter-declaration-clauses if either is reachable from the other.

13.7.2.4 Member classes of class templates [temp.mem.class]

1

#

A member class of a class template may be defined outside the class template definition in which it is declared.

[Note 1:

The member class must be defined before its first use that requires an instantiation ([temp.inst]).

For example,template struct A {class B;}; A::B* b1; // OK, requires A to be defined but not A::Btemplate class A::B { }; A::B b2; // OK, requires A::B to be defined

— end note]

13.7.2.5 Static data members of class templates [temp.static]

1

#

A definition for a static data member or static data member template may be provided in a namespace scope enclosing the definition of the static member's class template.

[Example 1: template class X {static T s;};template T X::s = 0;

struct limits {templatestatic const T min; // declaration};

templateconst T limits::min = { }; // definition — end example]

2

#

An explicit specialization of a static data member declared as an array of unknown bound can have a different bound from its definition, if any.

[Example 2: template struct A {static int i[];};template int A::i[4]; // 4 elementstemplate <> int A::i[] = { 1 }; // OK, 1 element — end example]

13.7.2.6 Enumeration members of class templates [temp.mem.enum]

1

#

An enumeration member of a class template may be defined outside the class template definition.

[Example 1: template struct A {enum E : T;};template enum A::E : T { e1, e2 }; A::E e = A::e1; — end example]

13.7.3 Member templates [temp.mem]

1

#

A template can be declared within a class or class template; such a template is called a member template.

A member template can be defined within or outside its class definition or class template definition.

A member template of a class template that is defined outside of its class template definition shall be specified with a template-head equivalent to that of the class template followed by a template-head equivalent to that of the member template ([temp.over.link]).

[Example 1: template struct string {template int compare(const T2&); template string(const string& s) { /* ... */ }};

template template int string::compare(const T2& s) {} — end example]

[Example 2: template concept C1 = true;template concept C2 = sizeof(T) <= 4;

template struct S {template void f(U); template void g(U);};

template templatevoid S::f(U) { } // OKtemplate templatevoid S::g(U) { } // error: no matching function in S — end example]

2

#

A local class of non-closure type shall not have member templates.

Access control rules apply to member template names.

A destructor shall not be a member template.

A non-template member function ([dcl.fct]) with a given name and type and a member function template of the same name, which could be used to generate a specialization of the same type, can both be declared in a class.

When both exist, a use of that name and type refers to the non-template member unless an explicit template argument list is supplied.

[Example 3: template struct A {void f(int); template void f(T2);};

template <> void A::f(int) { } // non-template member functiontemplate <> template <> void A::f<>(int) { } // member function template specializationint main() { A ac; ac.f(1); // non-template ac.f('c'); // template ac.f<>(1); // template} — end example]

3

#

A member function template shall not be declared virtual.

[Example 4: template struct AA {template virtual void g(C); // errorvirtual void f(); // OK}; — end example]

4

#

A specialization of a member function template does not override a virtual function from a base class.

[Example 5: class B {virtual void f(int);};

class D : public B {template void f(T); // does not override B::f(int)void f(int i) { f<>(i); } // overriding function that calls the function template specialization}; — end example]

5

#

[Note 1:

A specialization of a conversion function template is named in the same way as a non-template conversion function that converts to the same type ([class.conv.fct]).

[Example 6: struct A {template operator T*();};template A::operator T*() { return 0; }template <> A::operator char*() { return 0; } // specializationtemplate A::operator void*(); // explicit instantiationint main() { A a; int* ip; ip = a.operator int*(); // explicit call to template operator A::operator int*()} — end example]

An expression designating a particular specialization of a conversion function template can only be formed with a splice-expression.

There is no analogous syntax to form a template-id ([temp.names]) for such a function by providing an explicit template argument list ([temp.arg.explicit]).

— end note]

13.7.4 Variadic templates [temp.variadic]

1

#

A template parameter pack is a template parameter that accepts zero or more template arguments.

[Example 1: template<class ... Types> struct Tuple { };

Tuple<> t0; // Types contains no arguments Tuple t1; // Types contains one argument: int Tuple<int, float> t2; // Types contains two arguments: int and float Tuple<0> error; // error: 0 is not a type — end example]

2

#

A function parameter pack is a function parameter that accepts zero or more function arguments.

[Example 2: template<class ... Types> void f(Types ... args);

f(); // args contains no arguments f(1); // args contains one argument: int f(2, 1.0); // args contains two arguments: int and double — end example]

3

#

An init-capture pack is a lambda capture that introduces an init-capture for each of the elements in the pack expansion of its initializer.

[Example 3: template <typename... Args>void foo(Args... args) {[...xs=args]{ bar(xs...); // xs is an init-capture pack};} foo(); // xs contains zero init-captures foo(1); // xs contains one init-capture — end example]

4

#

A structured binding pack is an sb-identifier that introduces zero or more structured bindings ([dcl.struct.bind]).

[Example 4: auto foo() -> int(&)[2];

template void g() {auto [...a] = foo(); // a is a structured binding pack containing two elementsauto [b, c, ...d] = foo(); // d is a structured binding pack containing zero elements} — end example]

5

#

A pack is a template parameter pack, a function parameter pack, an init-capture pack, or a structured binding pack.

The number of elements of a template parameter pack or a function parameter pack is the number of arguments provided for the parameter pack.

The number of elements of an init-capture pack is the number of elements in the pack expansion of its initializer.

6

#

A pack expansion consists of a pattern and an ellipsis, the instantiation of which produces zero or more instantiations of the pattern in a list (described below).

The form of the pattern depends on the context in which the expansion occurs.

Pack expansions can occur in the following contexts:

if the template parameter pack is a parameter-declaration; the pattern is the parameter-declaration without the ellipsis;

if the template parameter pack is a type-parameter; the pattern is the corresponding type-parameter without the ellipsis;

if the template parameter pack is a template template parameter; the pattern is the correspondingtype-tt-parameter,variable-tt-parameter, orconcept-tt-parameter without the ellipsis.

[Example 5: template<class ... Types> void f(Types ... rest);template<class ... Types> void g(Types ... rest) { f(&rest ...); // “&rest ...'' is a pack expansion; “&rest'' is its pattern} — end example]

7

#

For the purpose of determining whether a pack satisfies a rule regarding entities other than packs, the pack is considered to be the entity that would result from an instantiation of the pattern in which it appears.

8

#

A pack whose name appears within the pattern of a pack expansion is expanded by that pack expansion.

An appearance of the name of a pack is only expanded by the innermost enclosing pack expansion.

The pattern of a pack expansion shall name one or more packs that are not expanded by a nested pack expansion; such packs are calledunexpanded packs in the pattern.

All of the packs expanded by a pack expansion shall have the same number of arguments specified.

An appearance of a name of a pack that is not expanded is ill-formed.

[Example 6: template<typename...> struct Tuple {};template<typename T1, typename T2> struct Pair {};

template<class ... Args1> struct zip {template<class ... Args2> struct with {typedef Tuple<Pair<Args1, Args2> ... > type; };};

typedef zip<short, int>::with<unsigned short, unsigned>::type T1; // T1 is Tuple<Pair<short, unsigned short>, Pair<int, unsigned>>typedef zip::with<unsigned short, unsigned>::type T2; // error: different number of arguments specified for Args1 and Args2template<class ... Args>void g(Args ... args) { // OK, Args is expanded by the function parameter pack args f(const_cast<const Args*>(&args)...); // OK, “Args'' and “args'' are expanded f(5 ...); // error: pattern does not contain any packs f(args); // error: pack “args'' is not expanded f(h(args ...) + args ...); // OK, first “args'' expanded within h,// second “args'' expanded within f} — end example]

9

#

The instantiation of a pack expansion considers items E1,E2,…,EN, whereN is the number of elements in the pack expansion parameters.

Each Ei is generated by instantiating the pattern and replacing each pack expansion parameter with its ith element.

Such an element, in the context of the instantiation, is interpreted as follows:

if the pack is a template parameter pack, the element is

a typedef-name for a type template parameter pack,

an id-expression for a constant template parameter pack, or

a template-name for a template template parameter pack

designating the ith corresponding type, constant, or template template argument;

if the pack is a function parameter pack, the element is anid-expression designating the ith function parameter that resulted from instantiation of the function parameter pack declaration;

if the pack is an init-capture pack, the element is an id-expression designating the variable introduced by the ith init-capture that resulted from instantiation of the init-capture pack declaration; otherwise

if the pack is a structured binding pack, the element is an id-expression designating the ith structured binding in the pack that resulted from the structured binding declaration.

When N is zero, the instantiation of a pack expansion does not alter the syntactic interpretation of the enclosing construct, even in cases where omitting the pack expansion entirely would otherwise be ill-formed or would result in an ambiguity in the grammar.

10

#

The instantiation of a sizeof... expression ([expr.sizeof]) produces an integral constant with value N.

11

#

When instantiating a pack-index-expression P, let K be the index of P.

The instantiation of P is the id-expression EK.

12

#

When instantiating a pack-index-specifier P, let K be the index of P.

The instantiation of P is the typedef-name EK.

13

#

The instantiation of an alignment-specifier with an ellipsis produces E1 E2 … EN.

14

#

The instantiation of a fold-expression ([expr.prim.fold]) produces:

( ((E1op E2)op ⋯)op EN) for a unary left fold,

( E1 op(⋯ op(EN−1 opEN))) for a unary right fold,

( (((Eop E1)op E2)op ⋯)op EN) for a binary left fold, and

( E1 op(⋯ op(EN−1 op(EN opE)))) for a binary right fold.

In each case,op is the fold-operator.

For a binary fold,E is generated by instantiating the cast-expression that did not contain an unexpanded pack.

[Example 7: template<typename ...Args>bool all(Args ...args) { return (... && args); }bool b = all(true, true, true, false);

Within the instantiation of all, the returned expression expands to((true && true) && true) && false, which evaluates to false.

— end example]

If N is zero for a unary fold, the value of the expression is shown in Table 20; if the operator is not listed in Table 20, the instantiation is ill-formed.

Table 20 — Value of folding empty sequences [tab:temp.fold.empty]

🔗
Operator
Value when pack is empty
🔗
&&
true
🔗
🔗
,
void()

15

#

A fold expanded constraint is not instantiated ([temp.constr.fold]).

16

#

The instantiation of any other pack expansion produces a list of elements E1,E2,…,EN.

[Note 1:

The variety of list varies with the context:expression-list,base-specifier-list,template-argument-list, etc.

— end note]

When N is zero, the instantiation of the expansion produces an empty list.

[Example 8: template<class... T> struct X : T... { };template<class... T> void f(T... values) { X<T...> x(values...);}template void f<>(); // OK, X<> has no base classes// x is a variable of type X<> that is value-initialized — end example]

13.7.5 Friends [temp.friend]

1

#

A friend of a class or class template can be a function template or class template, a specialization of a function template or class template, or a non-template function or class.

[Example 1: template class task;template task* preempt(task*);

template class task {friend void next_time(); friend void process(task); friend task preempt(task*); template friend int func(C); friend class task; template friend class frd;};

Here, each specialization of thetask class template has the functionnext_time as a friend; becauseprocess does not have explicittemplate-arguments, each specialization of thetask class template has an appropriately typed functionprocess as a friend, and this friend is not a function template specialization; because the friendpreempt has an explicittemplate-argumentT, each specialization of thetask class template has the appropriate specialization of the function templatepreempt as a friend; and each specialization of thetask class template has all specializations of the function templatefunc as friends.

Similarly, each specialization of thetask class template has the class template specializationtask as a friend, and has all specializations of the class templatefrd as friends.

— end example]

2

#

Friend classes, class templates, functions, or function templates can be declared within a class template.

When a template is instantiated, its friend declarations are found by name lookup as if the specialization had been explicitly declared at its point of instantiation.

[Note 1:

They can introduce entities that belong to an enclosing namespace scope ([dcl.meaning]), in which case they are attached to the same module as the class template ([module.unit]).

— end note]

3

#

A friend template may be declared within a class or class template.

A friend function template may be defined within a class or class template, but a friend class template may not be defined in a class or class template.

In these cases, all specializations of the friend class or friend function template are friends of the class or class template granting friendship.

[Example 2: class A {template friend class B; // OKtemplate friend void f(T) { /* ... */ } // OK}; — end example]

4

#

A template friend declaration specifies that all specializations of that template, whether they are implicitly instantiated ([temp.inst]), partially specialized ([temp.spec.partial]) or explicitly specialized ([temp.expl.spec]), are friends of the class containing the template friend declaration.

[Example 3: class X {template friend struct A; class Y { };};

template struct A { X::Y ab; }; // OKtemplate struct A<T*> { X::Y ab; }; // OK — end example]

5

#

A template friend declaration may declare a member of a dependent type to be a friend.

The friend declaration shall declare a function or specify a type with an elaborated-type-specifier, in either case with a nested-name-specifier ending with a simple-template-id, C, whose template-name names a class template.

The template parameters of the template friend declaration shall be deducible from C ([temp.deduct.type]).

In this case, a member of a specialization S of the class template is a friend of the class granting friendship if deduction of the template parameters of C from S succeeds, and substituting the deduced template arguments into the friend declaration produces a declaration that corresponds to the member of the specialization.

[Example 4: template struct A {struct B { }; void f(); struct D {void g(); }; T h(); template T i();};template<> struct A {struct B { }; int f(); struct D {void g(); }; template int i();};template<> struct A<float*> {int *h();};

class C {template friend struct A::B; // grants friendship to A::B even though// it is not a specialization of A::Btemplate friend void A::f(); // does not grant friendship to A::f()// because its return type does not matchtemplate friend void A::D::g(); // error: A::D does not end with a simple-template-idtemplate friend int A<T>::h(); // grants friendship to A<int*>::h() and A<float*>::h()template template // grants friendship to instantiations of A::i() andfriend T A::i(); // to A::i(), and thereby to all specializations}; // of those function templates — end example]

6

#

A friend template shall not be declared in a local class.

7

#

Friend declarations shall not declare partial specializations.

[Example 5: template class A { };class X {template friend class A<T*>; // error}; — end example]

8

#

When a friend declaration refers to a specialization of a function template, the function parameter declarations shall not include default arguments, nor shall the inline, constexpr, or consteval specifiers be used in such a declaration.

9

#

A non-template friend declaration with a requires-clause shall be a definition.

A friend function template with a constraint that depends on a template parameter from an enclosing template shall be a definition.

Such a constrained friend function or function template declaration does not declare the same function or function template as a declaration in any other scope.

13.7.6 Partial specialization [temp.spec.partial]

13.7.6.1 General [temp.spec.partial.general]

1

#

A partial specialization of a template provides an alternative definition of the template that is used instead of the primary definition when the arguments in a specialization match those given in the partial specialization ([temp.spec.partial.match]).

A declaration of the primary template shall precede any partial specialization of that template.

A partial specialization shall be reachable from any use of a template specialization that would make use of the partial specialization as the result of an implicit or explicit instantiation; no diagnostic is required.

2

#

Two partial specialization declarations declare the same entity if they are partial specializations of the same template and have equivalenttemplate-heads and template argument lists ([temp.over.link]).

Each partial specialization is a distinct template.

3

#

[Example 1: template<class T1, class T2, int I> class A { };template<class T, int I> class A<T, T*, I> { };template<class T1, class T2, int I> class A<T1*, T2, I> { };template class A<int, T*, 5> { };template<class T1, class T2, int I> class A<T1, T2*, I> { };

The first declaration declares the primary (unspecialized) class template.

The second and subsequent declarations declare partial specializations of the primary template.

— end example]

4

#

A partial specialization may be constrained ([temp.constr]).

[Example 2: template concept C = true;

template struct X { };template struct X<T*> { }; // #1template struct X { }; // #2

Both partial specializations are more specialized than the primary template.

#1 is more specialized because the deduction of its template arguments from the template argument list of the class template specialization succeeds, while the reverse does not.

#2 is more specialized because the template arguments are equivalent, but the partial specialization is more constrained ([temp.constr.order]).

— end example]

5

#

The template argument list of a partial specialization is the template-argument-list following the name of the template.

6

#

A partial specialization may be declared in any scope in which the corresponding primary template may be defined ([dcl.meaning], [class.mem], [temp.mem]).

[Example 3: template struct A {struct C {template struct B { }; template struct B<T2**> { }; // partial specialization #1};};

// partial specialization of A::C::Btemplate templatestruct A::C::B<T2*> { }; // #2 A::C::B<int*> absip; // uses partial specialization #2 — end example]

7

#

Partial specialization declarations do not introduce a name.

Instead, when the primary template name is used, any reachable partial specializations of the primary template are also considered.

[Note 1:

One consequence is that a using-declaration which refers to a class template does not restrict the set of partial specializations that are found through the using-declaration.

— end note]

[Example 4: namespace N {template<class T1, class T2> class A { }; // primary template}using N::A; // refers to the primary templatenamespace N {template class A<T, T*> { }; // partial specialization} A<int,int*> a; // uses the partial specialization, which is found through the using-declaration// which refers to the primary template — end example]

8

#

A constant template argument is non-specialized if it is the name of a constant template parameter.

All other constant template arguments are specialized.

9

#

Within the argument list of a partial specialization, the following restrictions apply:

  • (9.1)

    The type of a template parameter corresponding to a specialized constant template argument shall not be dependent on a parameter of the partial specialization. [Example 5: template <class T, T t> struct C {};template struct C<T, 1>; // errortemplate< int X, int (*array_ptr)[X] > class A {};int array[5];template< int X > class A<X,&array> { }; // error — end example]

  • (9.2)

    The partial specialization shall be more specialized than the primary template ([temp.spec.partial.order]).

  • (9.3)

    The template parameter list of a partial specialization shall not contain default template argument values.114

  • (9.4)

    An argument shall not contain an unexpanded pack. If an argument is a pack expansion ([temp.variadic]), it shall be the last argument in the template argument list.

10

#

The usual access checking rules do not apply to non-dependent names used to specify template arguments of the simple-template-id of the partial specialization.

[Note 2:

The template arguments can be private types or objects that would normally not be accessible.

Dependent names cannot be checked when declaring the partial specialization, but will be checked when substituting into the partial specialization.

— end note]

114)114)

There is no context in which they would be used.

13.7.6.2 Matching of partial specializations [temp.spec.partial.match]

1

#

When a template is used in a context that requires an instantiation of the template, it is necessary to determine whether the instantiation is to be generated using the primary template or one of the partial specializations.

This is done by matching the template arguments of the template specialization with the template argument lists of the partial specializations.

  • (1.1)

    If exactly one matching partial specialization is found, the instantiation is generated from that partial specialization.

  • (1.2)

    If more than one matching partial specialization is found, the partial order rules ([temp.spec.partial.order]) are used to determine whether one of the partial specializations is more specialized than the others. If such a partial specialization exists, the instantiation is generated from that partial specialization; otherwise, the use of the template is ambiguous and the program is ill-formed.

  • (1.3)

    If no matches are found, the instantiation is generated from the primary template.

2

#

A partial specialization matches a given actual template argument list if the template arguments of the partial specialization can bededuced from the actual template argument list, and the deduced template arguments satisfy the associated constraints of the partial specialization, if any.

[Example 1: template<class T1, class T2, int I> class A { }; // #1template<class T, int I> class A<T, T*, I> { }; // #2template<class T1, class T2, int I> class A<T1*, T2, I> { }; // #3template class A<int, T*, 5> { }; // #4template<class T1, class T2, int I> class A<T1, T2*, I> { }; // #5 A<int, int, 1> a1; // uses #1 A<int, int*, 1> a2; // uses #2, T is int, I is 1 A<int, char*, 5> a3; // uses #4, T is char A<int, char*, 1> a4; // uses #5, T1 is int, T2 is char, I is 1 A<int*, int*, 2> a5; // ambiguous: matches #3 and #5 — end example]

[Example 2: template concept C = requires (T t) { t.f(); };

template struct S { }; // #1template struct S { }; // #2struct Arg { void f(); };

S s1; // uses #1; the constraints of #2 are not satisfied S s2; // uses #2; both constraints are satisfied but #2 is more specialized — end example]

3

#

If the template arguments of a partial specialization cannot be deduced because of the structure of its template-parameter-list and the template-id, the program is ill-formed.

[Example 3: template <int I, int J> struct A {};template struct A<I+5, I2> {}; // errortemplate struct A<I, I> {}; // OKtemplate <int I, int J, int K> struct B {};template struct B<I, I2, 2> {}; // OK — end example]

4

#

In a name that refers to a specialization of a class or variable template (e.g., A<int, int, 1>), the argument list shall match the template parameter list of the primary template.

The template arguments of a partial specialization are deduced from the arguments of the primary template.

13.7.6.3 Partial ordering of partial specializations [temp.spec.partial.order]

1

#

For two partial specializations, the first is more specialized than the second if, given the following rewrite to two function templates, the first function template is more specialized than the second according to the ordering rules for function templates:

  • (1.1)

    Each of the two function templates has the same template parameters and associated constraints as the corresponding partial specialization.

  • (1.2)

    Each function template has a single function parameter whose type is a class template specialization where the template arguments are the corresponding template parameters from the function template for each template argument in the template-argument-list of the simple-template-id of the partial specialization.

2

#

[Example 1: template<int I, int J, class T> class X { };template<int I, int J> class X<I, J, int> { }; // #1template class X<I, I, int> { }; // #2template<int I0, int J0> void f(X<I0, J0, int>); // Atemplate void f(X<I0, I0, int>); // Btemplate class Y { };template <auto* p> class Y

{ }; // #3template <auto** pp> class Y { }; // #4template <auto* p0> void g(Y); // Ctemplate <auto** pp0> void g(Y); // D

According to the ordering rules for function templates, the function templateB is more specialized than the function templateA and the function templateD is more specialized than the function templateC.

Therefore, the partial specialization #2 is more specialized than the partial specialization #1 and the partial specialization #4 is more specialized than the partial specialization #3.

— end example]

[Example 2: template concept C = requires (T t) { t.f(); };template concept D = C && requires (T t) { t.f(); };

template class S { };template class S { }; // #1template class S { }; // #2template void f(S); // Atemplate void f(S); // B

The partial specialization #2 is more specialized than #1 because B is more specialized than A.

— end example]

13.7.6.4 Members of class template partial specializations [temp.spec.partial.member]

1

#

The members of the class template partial specialization are unrelated to the members of the primary template.

Class template partial specialization members that are used in a way that requires a definition shall be defined; the definitions of members of the primary template are never used as definitions for members of a class template partial specialization.

An explicit specialization of a member of a class template partial specialization is declared in the same way as an explicit specialization of a member of the primary template.

[Example 1: // primary class templatetemplate<class T, int I> struct A {void f();};

// member of primary class templatetemplate<class T, int I> void A<T,I>::f() { }// class template partial specializationtemplate struct A<T,2> {void f(); void g(); void h();};

// member of class template partial specializationtemplate void A<T,2>::g() { }// explicit specializationtemplate<> void A<char,2>::h() { }int main() { A<char,0> a0; A<char,2> a2; a0.f(); // OK, uses definition of primary template's member a2.g(); // OK, uses definition of partial specialization's member a2.h(); // OK, uses definition of explicit specialization's member a2.f(); // error: no definition of f for A<T,2>; the primary template is not used here} — end example]

2

#

If a member template of a class template is partially specialized, the member template partial specializations are member templates of the enclosing class template; if the enclosing class template is instantiated ([temp.inst], [temp.explicit]), a declaration for every member template partial specialization is also instantiated as part of creating the members of the class template specialization.

If the primary member template is explicitly specialized for a given (implicit) specialization of the enclosing class template, the partial specializations of the member template are ignored for this specialization of the enclosing class template.

If a partial specialization of the member template is explicitly specialized for a given (implicit) specialization of the enclosing class template, the primary member template and its other partial specializations are still considered for this specialization of the enclosing class template.

[Example 2: template struct A {template struct B {}; // #1template struct B<T2*> {}; // #2};

template<> template struct A::B {}; // #3 A::B<int*> abcip; // uses #2 A::B<int*> absip; // uses #3 A::B abci; // uses #1 — end example]

13.7.7 Function templates [temp.fct]

13.7.7.1 General [temp.fct.general]

1

#

A function template defines an unbounded set of related functions.

[Example 1:

A family of sort functions can be declared like this:template class Array { };template void sort(Array&);

— end example]

2

#

[Note 1:

A function template can have the same name as other function templates and non-template functions ([dcl.fct]) in the same scope.

— end note]

A non-template function is not related to a function template (i.e., it is never considered to be a specialization), even if it has the same name and type as a potentially generated function template specialization.115

115)115)

That is, declarations of non-template functions do not merely guide overload resolution of function template specializations with the same name.

If such a non-template function is odr-used ([basic.def.odr]) in a program, it must be defined; it will not be implicitly instantiated using the function template definition.

1

#

It is possible to overload function templates so that two different function template specializations have the same type.

[Example 1:

// translation unit 1:templatevoid f(T*);void g(int* p) { f(p); // calls f(int*)}

// translation unit 2:templatevoid f(T);void h(int* p) { f(p); // calls f<int*>(int*)}

— end example]

2

#

Such specializations are distinct functions and do not violate theone-definition rule.

3

#

The signature of a function template is defined in [intro.defs].

The names of the template parameters are significant only for establishing the relationship between the template parameters and the rest of the signature.

[Note 1:

Two distinct function templates can have identical function return types and function parameter lists, even if overload resolution alone cannot distinguish them.

template void f();template void f(); // OK, overloads the first template// distinguishable with an explicit template argument list — end note]

4

#

When an expression that references a template parameter is used in the function parameter list or the return type in the declaration of a function template, the expression that references the template parameter is part of the signature of the function template.

This is necessary to permit a declaration of a function template in one translation unit to be linked with another declaration of the function template in another translation unit and, conversely, to ensure that function templates that are intended to be distinct are not linked with one another.

[Example 2: template <int I, int J> A<I+J> f(A, A); // #1template <int K, int L> A<K+L> f(A, A); // same as #1template <int I, int J> A f(A, A); // different from #1 — end example]

[Note 2:

Most expressions that use template parameters use constant template parameters, but it is possible for an expression to reference a type parameter.

For example, a template type parameter can be used in thesizeof operator.

— end note]

5

#

Two expressions involving template parameters are consideredequivalent if two function definitions containing the expressions would satisfy the one-definition rule, except that the tokens used to name the template parameters may differ as long as a token used to name a template parameter in one expression is replaced by another token that names the same template parameter in the other expression.

Two unevaluated operands that do not involve template parameters are considered equivalent if two function definitions containing the expressions would satisfy the one-definition rule, except that the tokens used to name types and declarations may differ as long as they name the same entities, and the tokens used to form concept-ids ([temp.names]) may differ as long as the two template-ids are the same ([temp.type]).

[Note 3:

For instance, A<42> and A<40+2> name the same type.

— end note]

Two lambda-expressions are never considered equivalent.

[Note 4:

The intent is to avoid lambda-expressions appearing in the signature of a function template with external linkage.

— end note]

For determining whether two dependent names ([temp.dep]) are equivalent, only the name itself is considered, not the result of name lookup.

[Note 5:

If such a dependent name is unqualified, it is looked up from a first declaration of the function template ([temp.res.general]).

— end note]

[Example 3: template <int I, int J> void f(A<I+J>); // #1template <int K, int L> void f(A<K+L>); // same as #1template decltype(g(T())) h();int g(int);template decltype(g(T())) h() // redeclaration of h() uses the earlier lookup…{ return g(T()); } // … although the lookup here does find g(int)int i = h(); // template argument substitution fails; g(int)// not considered at the first declaration of h()// ill-formed, no diagnostic required: the two expressions are functionally equivalent but not equivalenttemplate void foo(const char (*s)[([]{}, N)]);template void foo(const char (*s)[([]{}, N)]);

// two different declarations because the non-dependent portions are not considered equivalenttemplate void spam(decltype([]{}) (*s)[sizeof(T)]);template void spam(decltype([]{}) (*s)[sizeof(T)]); — end example]

Two potentially-evaluated expressions involving template parameters that are not equivalent arefunctionally equivalent if, for any given set of template arguments, the evaluation of the expression results in the same value.

Two unevaluated operands that are not equivalent are functionally equivalent if, for any given set of template arguments, the expressions perform the same operations in the same order with the same entities.

[Note 6:

For instance, one could have redundant parentheses.

— end note]

[Example 4: template concept C = true;template struct A {void f() requires C<42>; // #1void f() requires true; // OK, different functions}; — end example]

6

#

Two template-heads areequivalent if their template-parameter-lists have the same length, corresponding template-parameters are equivalent and are both declared with type-constraints that are equivalent if either template-parameter is declared with a type-constraint, and if either template-head has a requires-clause, they both haverequires-clauses and the correspondingconstraint-expressions are equivalent.

Two template-parameters areequivalent under the following conditions:

they declare template parameters of the same kind,

if either declares a template parameter pack, they both do,

if they declare constant template parameters, they have equivalent types ignoring the use of type-constraints for placeholder types, and

if they declare template template parameters, their template-heads are equivalent.

When determining whether types or type-constraints are equivalent, the rules above are used to compare expressions involving template parameters.

Two template-heads arefunctionally equivalent if they accept and are satisfied by ([temp.constr.constr]) the same set of template argument lists.

7

#

If the validity or meaning of the program depends on whether two constructs are equivalent, and they are functionally equivalent but not equivalent, the program is ill-formed, no diagnostic required.

Furthermore, if two declarations A and B of function templates

introduce the same name,

have corresponding signatures ([basic.scope.scope]),

would declare the same entity, when considering A and B to correspond in that determination ([basic.link]), and

accept and are satisfied by the same set of template argument lists,

but do not correspond, the program is ill-formed, no diagnostic required.

8

#

[Note 7:

This rule guarantees that equivalent declarations will be linked with one another, while not requiring implementations to use heroic efforts to guarantee that functionally equivalent declarations will be treated as distinct.

For example, the last two declarations are functionally equivalent and would cause a program to be ill-formed:// guaranteed to be the sametemplate void f(A, A<I+10>);template void f(A, A<I+10>);

// guaranteed to be differenttemplate void f(A, A<I+10>);template void f(A, A<I+11>);

// ill-formed, no diagnostic requiredtemplate void f(A, A<I+10>);template void f(A, A<I+1+2+3+4>);

— end note]

13.7.7.3 Partial ordering of function templates [temp.func.order]

1

#

If multiple function templates share a name, the use of that name can be ambiguous because template argument deduction ([temp.deduct]) may identify a specialization for more than one function template.

Partial ordering of overloaded function template declarations is used in the following contexts to select the function template to which a function template specialization refers:

during overload resolution for a call to a function template specialization ([over.match.best]);

when the address of a function template specialization is taken;

when a placement operator delete that is a function template specialization is selected to match a placement operator new ([basic.stc.dynamic.deallocation], [expr.new]);

when a friend function declaration, anexplicit instantiation or an explicit specialization refers to a function template specialization.

2

#

Partial ordering selects which of two function templates is more specialized than the other by transforming each template in turn (see next paragraph) and performing template argument deduction using the function type.

The deduction process determines whether one of the templates is more specialized than the other.

If so, the more specialized template is the one chosen by the partial ordering process.

If both deductions succeed, the partial ordering selects the more constrained template (if one exists) as determined below.

3

#

To produce the transformed template, for each type, constant, type template, variable template, or concept template parameter (including template parameter packs ([temp.variadic]) thereof) synthesize a unique type, value, class template, variable template, or concept, respectively, and substitute it for each occurrence of that parameter in the function type of the template.

[Note 1:

The type replacing the placeholder in the type of the value synthesized for a constant template parameter is also a unique synthesized type.

— end note]

4

#

A synthesized template has the same template-head as its corresponding template template parameter.

5

#

Each function template M that is a member function is considered to have a new first parameter of type X(M), described below, inserted in its function parameter list.

If exactly one of the function templates was considered by overload resolution via a rewritten candidate ([over.match.oper]) with a reversed order of parameters, then the order of the function parameters in its transformed template is reversed.

For a function template M with cv-qualifiers cv that is a member of a class A:

  • (5.1)

    The type X(M) is “rvalue reference to cv A” if the optional ref-qualifier ofM is && or if M has no ref-qualifier and the positionally-corresponding parameter of the other transformed template has rvalue reference type; if this determination depends recursively upon whether X(M) is an rvalue reference type, it is not considered to have rvalue reference type.

  • (5.2)

    Otherwise, X(M) is “lvalue reference to cv A”.

[Note 2:

This allows a non-static member to be ordered with respect to a non-member function and for the results to be equivalent to the ordering of two equivalent non-members.

— end note]

[Example 1: struct A { };template struct B {template int operator*(R&); // #1};

template<class T, class R> int operator*(T&, R&); // #2// The declaration of B::operator* is transformed into the equivalent of// template int operator*(B&, R&); // #1aint main() { A a; B b; b * a; // calls #1} — end example]

6

#

Using the transformed function template's function type, perform type deduction against the other template as described in [temp.deduct.partial].

[Example 2: template struct A { A(); };

template void f(T);template void f(T*);template void f(const T*);

template void g(T);template void g(T&);

template void h(const T&);template void h(A&);

void m() {const int* p; f(p); // f(const T*) is more specialized than f(T) or f(T*)float x; g(x); // ambiguous: g(T) or g(T&) A z; h(z); // overload resolution selects h(A&)const A z2; h(z2); // h(const T&) is called because h(A&) is not callable} — end example]

7

#

[Note 3:

Since, in a call context, such type deduction considers only parameters for which there are explicit call arguments, some parameters are ignored (namely, function parameter packs, parameters with default arguments, and ellipsis parameters).

[Example 3: template void f(T); // #1template void f(T*, int=1); // #2template void g(T); // #3template void g(T*, ...); // #4int main() {int* ip; f(ip); // calls #2 g(ip); // calls #4} — end example]

[Example 4: template<class T, class U> struct A { };

template<class T, class U> void f(U, A<U, T>* p = 0); // #1template< class U> void f(U, A<U, U>* p = 0); // #2template void g(T, T = T()); // #3template<class T, class... U> void g(T, U ...); // #4void h() { f(42, (A<int, int>*)0); // calls #2 f(42); // error: ambiguous g(42); // error: ambiguous} — end example]

[Example 5: template<class T, class... U> void f(T, U...); // #1template void f(T); // #2template<class T, class... U> void g(T*, U...); // #3template void g(T); // #4void h(int i) { f(&i); // OK, calls #2 g(&i); // OK, calls #3} — end example]

— end note]

8

#

If deduction against the other template succeeds for both transformed templates, constraints can be considered as follows:

If exactly one of the templates was considered by overload resolution via a rewritten candidate with reversed order of parameters: + (8.2.1.1) If, for either template, some of the template parameters are not deducible from their function parameters, neither template is more specialized than the other.

+
      [(8.2.1.2)](#temp.func.order-8.2.1.2)

If there is either no reordering or more than one reordering of the associated template-parameter-list such that - (8.2.1.2.1)

the corresponding template-parameters of the template-parameter-lists are equivalent and

  - [(8.2.1.2.2)](#temp.func.order-8.2.1.2.2)

the function parameters that positionally correspond between the two templates are of the same type,

neither template is more specialized than the other.

Otherwise, if the corresponding template-parameters of the template-parameter-lists are not equivalent ([temp.over.link]) or if the function parameters that positionally correspond between the two templates are not of the same type, neither template is more specialized than the other.

  • (8.3)

    Otherwise, if the context in which the partial ordering is done is that of a call to a conversion function and the return types of the templates are not the same, then neither template is more specialized than the other.

  • (8.4)

    Otherwise, if one template is more constrained than the other ([temp.constr.order]), the more constrained template is more specialized than the other.

  • (8.5)

    Otherwise, neither template is more specialized than the other.

[Example 6: template constexpr bool True = true;template concept C = True;

void f(C auto &, auto &) = delete;template void f(Q &, C auto &);

void g(struct A *ap, struct B *bp) { f(*ap, *bp); // OK, can use different methods to produce template parameters}template <typename T, typename U> struct X {};

template <typename T, C U, typename V> bool operator==(X<T, U>, V) = delete;template <C T, C U, C V> bool operator==(T, X<U, V>);

void h() { X<void *, int>{} == 0; // OK, correspondence of [T, U, V] and [U, V, T]} — end example]

13.7.8 Alias templates [temp.alias]

1

#

A template-declaration in which the declaration is analias-declaration ([dcl.pre]) declares theidentifier to be an alias template.

An alias template is a name for a family of types.

The name of the alias template is a template-name.

2

#

A

template-id that is not the operand of a reflect-expression or

splice-specialization-specifier

that designates the specialization of an alias template is equivalent to the associated type obtained by substitution of its template-arguments for thetemplate-parameters in the defining-type-id of the alias template.

Any other template-id that names a specialization of an alias template is a typedef-name for a type alias.

[Note 1:

An alias template name is never deduced.

— end note]

[Example 1: template struct Alloc { /* ... / };template using Vec = vector<T, Alloc>; Vec v; // same as vector<int, Alloc> v;templatevoid process(Vec& v){ / ... / }templatevoid process(vector<T, Alloc>& w){ / ... */ } // error: redefinitiontemplate<template class TT>void f(TT);

f(v); // error: Vec not deducedtemplate<template<class,class> class TT>void g(TT<int, Alloc>); g(v); // OK, TT = vector — end example]

3

#

However, if the template-id is dependent, subsequent template argument substitution still applies to the template-id.

[Example 2: template<typename...> using void_t = void;template void_t f(); f(); // error: int does not have a nested type foo — end example]

4

#

The defining-type-id in an alias template declaration shall not refer to the alias template being declared.

The type produced by an alias template specialization shall not directly or indirectly make use of that specialization.

[Example 3: template struct A;template using B = typename A::U;template struct A {typedef B U;}; B b; // error: instantiation of B uses own type via A::U — end example]

5

#

The type of a lambda-expression appearing in an alias template declaration is different between instantiations of that template, even when the lambda-expression is not dependent.

[Example 4: template using A = decltype([] { }); // A and A refer to different closure types — end example]

13.7.9 Concept definitions [temp.concept]

1

#

A concept is a template that defines constraints on its template arguments.

concept-definition:
concept concept-name attribute-specifier-seqopt = constraint-expression ;

concept-name:
identifier

2

#

A concept-definition declares a concept.

Its identifier becomes a concept-name referring to that concept within its scope.

The optional attribute-specifier-seq appertains to the concept.

[Example 1: templateconcept C = requires(T x) {{ x == x } -> std::convertible_to;};

templaterequires C // C constrains f1(T) in constraint-expression T f1(T x) { return x; }template // C, as a type-constraint, constrains f2(T) T f2(T x) { return x; } — end example]

3

#

A concept-definition shall inhabit a namespace scope ([basic.scope.namespace]).

4

#

A concept shall not have associated constraints.

5

#

A concept is not instantiated ([temp.spec]).

[Note 1:

A concept-id ([temp.names]) is evaluated as an expression.

A concept cannot be explicitly instantiated ([temp.explicit]), explicitly specialized ([temp.expl.spec]), or partially specialized ([temp.spec.partial]).

— end note]

6

#

The constraint-expression of a concept-definition is an unevaluated operand ([expr.context]).

7

#

The first declared template parameter of a concept definition is itsprototype parameter.

A type concept is a concept whose prototype parameter is a type template parameter.