%!TEX root = std.tex
\rSec0[temp]{Templates}%
\indextext{template|(}

\gramSec[gram.temp]{Templates}

\indextext{parameterized type|see{template}}%
\indextext{type generator|see{template}}

\rSec1[temp.pre]{Preamble}

\pnum
A \defn{template} defines a family of classes, functions, or variables,
an alias for a family of types, or a concept.

\indextext{\idxcode{template}}%
%
\begin{bnf}
\nontermdef{template-declaration}\br
  template-head declaration\br
  template-head concept-definition
\end{bnf}

\begin{bnf}
\nontermdef{template-head}\br
  \keyword{template} \terminal{<} template-parameter-list \terminal{>} \opt{requires-clause}
\end{bnf}

\begin{bnf}
\nontermdef{template-parameter-list}\br
  template-parameter\br
  template-parameter-list \terminal{,} template-parameter
\end{bnf}

\begin{bnf}
\nontermdef{requires-clause}\br
  \keyword{requires} constraint-logical-or-expression
\end{bnf}

\begin{bnf}
\nontermdef{constraint-logical-or-expression}\br
  constraint-logical-and-expression\br
  constraint-logical-or-expression \terminal{||} constraint-logical-and-expression
\end{bnf}

\begin{bnf}
\nontermdef{constraint-logical-and-expression}\br
  primary-expression\br
  constraint-logical-and-expression \terminal{\&\&} primary-expression
\end{bnf}

\begin{note}
The \tcode{>} token following the
\grammarterm{template-parameter-list} of a
\grammarterm{template-declaration}
can be the product of replacing a
\tcode{>>} token by two consecutive \tcode{>}
tokens\iref{temp.names}.
\end{note}

\pnum
The \grammarterm{declaration} in a \grammarterm{template-declaration} (if any)
shall
\begin{itemize}
\item declare or define a function, a class, or a variable, or

\item define a member function, a member class, a member enumeration, or a static data member of a
class template or of a class nested within a class template, or

\item define a member template of a class or class template, or

\item be a \grammarterm{friend-type-declaration}, or

\item be a \grammarterm{deduction-guide}, or

\item be an \grammarterm{alias-declaration}.
\end{itemize}

\pnum
A \grammarterm{template-declaration} is a \grammarterm{declaration}.
A declaration introduced by a template declaration of a
\indextext{variable template!definition of}%
variable is a \defnx{variable template}{template!variable}. A variable template at class scope is a
\defnx{static data member template}{template!static data member}.

\begin{example}
\begin{codeblock}
template<class T>
  constexpr T pi = T(3.1415926535897932385L);
template<class T>
  T circular_area(T r) {
    return pi<T> * r * r;
  }
struct matrix_constants {
  template<class T>
    using pauli = hermitian_matrix<T, 2>;
  template<class T>
    constexpr static pauli<T> sigma1 = { { 0, 1 }, { 1, 0 } };
  template<class T>
    constexpr static pauli<T> sigma2 = { { 0, -1i }, { 1i, 0 } };
  template<class T>
    constexpr static pauli<T> sigma3 = { { 1, 0 }, { 0, -1 } };
};
\end{codeblock}
\end{example}

\pnum
\begin{note}
A \grammarterm{template-declaration}
can appear only as a namespace scope or class scope declaration.
\end{note}
Its \grammarterm{declaration} shall not be an
\grammarterm{export-declaration}.
In a function template declaration, the \grammarterm{unqualified-id} of the
\grammarterm{declarator-id} shall be a name.
\begin{note}
A class or variable template declaration of a \grammarterm{simple-template-id}
declares a partial specialization\iref{temp.spec.partial}.
\end{note}

\pnum
In a
\grammarterm{template-declaration},
explicit specialization, or explicit instantiation, the
\grammarterm{init-declarator-list}
in the declaration shall contain at most one declarator.
When such a declaration is used to declare a class template,
no declarator is permitted.
In a \grammarterm{template-declaration}
whose \grammarterm{declaration} is a \grammarterm{friend-type-declaration},
the \grammarterm{friend-type-declaration} shall be of the form
\begin{ncsimplebnf}
\keyword{friend} friend-type-specifier \terminal{;}
\end{ncsimplebnf}
\begin{example}
\begin{codeblock}
template<class ...>
struct C {
  struct Nested { };
};

template<class ... Us>
struct S {
  template <typename ...Ts>
  friend class C<Ts>::Nested...;        // error: pack expansion is not a \grammarterm{friend-type-specifier}
  friend class C<Us>::Nested...;        // OK, not a \grammarterm{template-declaration}
};
\end{codeblock}
\end{example}

\pnum
\indextext{template name!linkage of}%
A specialization (explicit or implicit) of one template is
distinct from all specializations of any other template.
A template, an explicit specialization\iref{temp.expl.spec}, and a
partial specialization shall not have C language linkage.
\begin{note}
Default arguments for function templates and for member functions of
class templates are considered definitions for the purpose of template
instantiation\iref{temp.decls} and must obey the one-definition rule\iref{basic.def.odr}.
\end{note}

\pnum
\begin{note}
A template cannot have the same name as any other
name bound in the same scope\iref{basic.scope.scope}, except
that a function template can share a name with \grammarterm{using-declarator}s,
a type, non-template functions\iref{dcl.fct} and/or function templates\iref{temp.over}.
Specializations, including partial specializations\iref{temp.spec.partial},
do not reintroduce or bind names.
Their target scope is the target scope of the primary template,
so all specializations of a template belong to the same scope as it does.
\begin{example}
\begin{codeblock}
void f() {}
class f {};                                     // OK
namespace N {
  void f(int) {}
}
using N::f;                                     // OK
template<typename> void f(long) {}              // \#1, OK
template<typename> void f(long) {}              // error: redefinition of \#1
template<typename> void f(long long) {}         // OK
template<>         void f<int>(long long) {}    // OK, doesn't bind a name
\end{codeblock}
\end{example}
\end{note}

\pnum
\indextext{entity!templated}%
An entity is \defn{templated}
if it is
\begin{itemize}
\item a template,
\item an entity defined\iref{basic.def} or created\iref{class.temporary}
      within the \grammarterm{compound-statement}
      of an \grammarterm{expansion-statement}\iref{stmt.expand},
\item an entity defined or created in a templated entity,
\item a member of a templated entity,
\item an enumerator for an enumeration that is a templated entity, or
\item the closure type of a \grammarterm{lambda-expression}\iref{expr.prim.lambda.closure}
      appearing in the declaration of a templated entity.
\end{itemize}

\begin{note}
A local class, a local or block variable, or a friend function defined in a
templated entity is a templated entity.
\end{note}

A \defnadj{templated}{function} is
a function template or a function that is templated.
A \defnadj{templated}{class} is
a class template or a class that is templated.
A \defnadj{templated}{variable} is
a variable template or a variable that is templated.

\pnum
A \grammarterm{template-declaration} is written
in terms of its template parameters.
The optional \grammarterm{requires-clause} following a
\grammarterm{template-parameter-list} allows the specification of
constraints\iref{temp.constr.decl} on template arguments\iref{temp.arg}.
The \grammarterm{requires-clause} introduces the
\grammarterm{constraint-expression} that results from interpreting
the \grammarterm{constraint-logical-or-expression} as a
\grammarterm{constraint-expression}.
The \grammarterm{constraint-logical-or-expression} of a
\grammarterm{requires-clause} is an unevaluated operand\iref{expr.context}.
\begin{note}
The expression in a \grammarterm{requires-clause}
uses a restricted grammar to avoid ambiguities.
Parentheses can be used to specify arbitrary expressions
in a \grammarterm{requires-clause}.
\begin{example}
\begin{codeblock}
template<int N> requires N == sizeof new unsigned short
int f();            // error: parentheses required around \tcode{==} expression
\end{codeblock}
\end{example}
\end{note}

\pnum
A definition of
a function template,
member function of a class template,
variable template,
or static data member of a class template
shall be reachable from the end of every definition domain\iref{basic.def.odr}
in which it is implicitly instantiated\iref{temp.inst} unless the
corresponding specialization is explicitly instantiated\iref{temp.explicit}
in some translation unit; no diagnostic is required.

\rSec1[temp.param]{Template parameters}

\pnum
The syntax for
\grammarterm{template-parameter}{s}
is:

\begin{bnf}
\nontermdef{template-parameter}\br
  type-parameter\br
  parameter-declaration\br
  type-tt-parameter\br
  variable-tt-parameter\br
  concept-tt-parameter
\end{bnf}

\begin{bnf}
\nontermdef{type-parameter}\br
  type-parameter-key \opt{\terminal{...}} \opt{identifier}\br
  type-parameter-key \opt{identifier} \terminal{=} type-id\br
  type-constraint \opt{\terminal{...}} \opt{identifier}\br
  type-constraint \opt{identifier} \terminal{=} type-id
\end{bnf}

\begin{bnf}
\nontermdef{type-parameter-key}\br
  \keyword{class}\br
  \keyword{typename}
\end{bnf}

\begin{bnf}
\nontermdef{type-constraint}\br
  \opt{nested-name-specifier} concept-name\br
  \opt{nested-name-specifier} concept-name \terminal{<} \opt{template-argument-list} \terminal{>}
\end{bnf}

\begin{bnf}
\nontermdef{type-tt-parameter}\br
  template-head type-parameter-key \opt{\terminal{...}} \opt{identifier}\br
  template-head type-parameter-key \opt{identifier} type-tt-parameter-default
\end{bnf}

\begin{bnf}
\nontermdef{type-tt-parameter-default}\br
  \terminal{=} \opt{nested-name-specifier} template-name\br
  \terminal{=} nested-name-specifier \terminal{template} template-name
\end{bnf}

\begin{bnf}
\nontermdef{variable-tt-parameter}\br
  template-head \terminal{auto} \opt{\terminal{...}} \opt{identifier}\br
  template-head \terminal{auto} \opt{identifier} \terminal{=} \opt{nested-name-specifier} template-name
\end{bnf}

\begin{bnf}
\nontermdef{concept-tt-parameter}\br
  \terminal{template} \terminal{<} template-parameter-list \terminal{>} \terminal{concept} \opt{\terminal{...}} \opt{identifier}\br
  \terminal{template} \terminal{<} template-parameter-list \terminal{>} \terminal{concept} \opt{identifier} \terminal{=} \opt{nested-name-specifier} template-name
\end{bnf}

\indextext{component name}%
The component names of a \grammarterm{type-constraint} are
its \grammarterm{concept-name} and
those of its \grammarterm{nested-name-specifier} (if any).
\begin{note}
The \tcode{>} token following the
\grammarterm{template-parameter-list} of a
\grammarterm{type-tt-parameter},
\grammarterm{variable-tt-parameter}, or
\grammarterm{concept-tt-parameter}
can be the product of replacing a
\tcode{>>} token by two consecutive \tcode{>}
tokens\iref{temp.names}.
\end{note}

\pnum
%FIXME: "is" or "shall be"? i.e., what if it's not?
%FIXME: Note: we don't appear to ever define what a "template parameter" is;
%FIXME: is this supposed to be the definition for template parameter?
A template parameter is of one of the following kinds:
\begin{itemize}
\item
A \defnadj{type}{template parameter} is
a template parameter introduced by a \grammarterm{type-parameter}.
\item
A \defnadj{constant}{template parameter} is
a template parameter introduced by a \grammarterm{parameter-declaration}.
\item
A \defnadj{type template}{template parameter} is
a template parameter introduced by a \grammarterm{type-tt-parameter}.
\item
A \defnadj{variable template}{template parameter} is
a template parameter introduced by a \grammarterm{variable-tt-parameter}.
\item
A \defnadj{concept}{template parameter} is
a template parameter introduced by a \grammarterm{concept-tt-parameter}.
\end{itemize}

\pnum
Type template template parameters,
variable template template parameters, and
concept template parameters
are collectively referred to as \defnadj{template}{template parameters}.

\pnum
The \grammarterm{nested-name-specifier} of a \grammarterm{type-constraint},
if any, shall not be dependent.

\pnum
A concept template parameter shall not have
associated constraints\iref{temp.constr.decl}.

\pnum
If a \grammarterm{template-parameter} is
a \grammarterm{parameter-declaration} that declares a pack\iref{dcl.fct}, or
otherwise has an ellipsis prior to its optional \grammarterm{identifier},
then the \grammarterm{template-parameter}
declares a template parameter pack\iref{temp.variadic}.
A template parameter pack that is a \grammarterm{parameter-declaration} whose type
contains one or more unexpanded packs is a pack expansion. Similarly,
a template parameter pack that is a template template parameter with a
\grammarterm{template-parameter-list} containing one or more unexpanded
packs is a pack expansion.
A type parameter pack with a \grammarterm{type-constraint} that
contains an unexpanded parameter pack is a pack expansion.
A template parameter pack that is a pack
expansion shall not expand a template parameter pack declared in the same
\grammarterm{template-parameter-list}.
\begin{example}
\begin{codeblock}
template <class... Types>                       // \tcode{Types} is a template type parameter pack
   class Tuple;                                 // but not a pack expansion

template <class T, int... Dims>                 // \tcode{Dims} is a constant template parameter pack
   struct multi_array;                          // but not a pack expansion

template <class... T>
  struct value_holder {
    template <T... Values> struct apply { };    // \tcode{Values} is a constant template parameter pack
  };                                            // and a pack expansion

template <class... T, T... Values>              // error: \tcode{Values} expands template type parameter
  struct static_array;                          // pack \tcode{T} within the same template parameter list
\end{codeblock}
\end{example}

\pnum
There is no semantic difference between
\keyword{class}
and
\keyword{typename}
in a
\grammarterm{type-parameter-key}.
\keyword{typename}
followed by an
\grammarterm{unqualified-id}
names a template type parameter.
\keyword{typename}
followed by a
\grammarterm{qualified-id}
denotes the type in a
\grammarterm{parameter-declaration}.
A \grammarterm{template-parameter} of the form
\keyword{class} \grammarterm{identifier} is a \grammarterm{type-parameter}.
\begin{example}
\begin{codeblock}
class T { @\commentellip@ };
int i;

template<class T, T i> void f(T t) {
  T t1 = i;         // template parameters \tcode{T} and \tcode{i}
  ::T t2 = ::i;     // global namespace members \tcode{T} and \tcode{i}
}
\end{codeblock}
Here, the template \tcode{f} has a type template parameter
called \tcode{T}, rather than an unnamed constant
template parameter of class \tcode{T}.
\end{example}
The \grammarterm{parameter-declaration} of a \grammarterm{template-parameter}
shall not have a \grammarterm{storage-class-specifier}.
Types shall not be defined in a template parameter
declaration.

\pnum
The \grammarterm{identifier} in
a \grammarterm{template-parameter} denoting a type or template
is not looked up.
An \grammarterm{identifier} that does not follow an ellipsis
is defined to be
\begin{itemize}
\item
a \grammarterm{typedef-name} for a \grammarterm{type-parameter},
\item
a \grammarterm{template-name} for a \grammarterm{variable-tt-parameter},
\item
a \grammarterm{template-name} for a \grammarterm{type-tt-parameter}, or
\item
a \grammarterm{concept-name} for a \grammarterm{concept-tt-parameter},
\end{itemize}
in the scope of the template declaration.

\pnum
A \grammarterm{type-constraint} \tcode{Q} that designates a concept \tcode{C}
can be used to constrain a
contextually-determined type or template type parameter pack \tcode{T}
with a \grammarterm{constraint-expression} \tcode{E} defined as follows.
If \tcode{Q} is of the form \tcode{C<A$_1$, $\dotsc$, A$_n$>},
then let \tcode{E$'$} be \tcode{C<T, A$_1$, $\dotsc$, A$_n$>}.
Otherwise, let \tcode{E$'$} be \tcode{C<T>}.
If \tcode{T} is not a pack,
then \tcode{E} is \tcode{E$'$},
otherwise \tcode{E} is \tcode{(E$'$ \&\& ...)}.
This \grammarterm{constraint-expression} \tcode{E} is called the
\defnx{immediately-declared constraint}{constraint!immediately-declared}
of \tcode{Q} for \tcode{T}.
The concept designated by a \grammarterm{type-constraint}
shall be a type concept\iref{temp.concept}.

\pnum
A \grammarterm{type-parameter} that starts with a \grammarterm{type-constraint}
introduces the immediately-declared constraint
of the \grammarterm{type-constraint} for the parameter.
\begin{example}
\begin{codeblock}
template<typename T> concept C1 = true;
template<typename... Ts> concept C2 = true;
template<typename T, typename U> concept C3 = true;

template<C1 T> struct s1;               // associates \tcode{C1<T>}
template<C1... T> struct s2;            // associates \tcode{(C1<T> \&\& ...)}
template<C2... T> struct s3;            // associates \tcode{(C2<T> \&\& ...)}
template<C3<int> T> struct s4;          // associates \tcode{C3<T, int>}
template<C3<int>... T> struct s5;       // associates \tcode{(C3<T, int> \&\& ...)}
\end{codeblock}
\end{example}

\pnum
A constant template parameter
shall have one of the following (possibly cv-qualified) types:
\begin{itemize}
\item a structural type (see below),
\item a type that contains a placeholder type\iref{dcl.spec.auto}, or
\item a placeholder for a deduced class type\iref{dcl.type.class.deduct}.
\end{itemize}
The top-level
\grammarterm{cv-qualifier}{s}
on the
\grammarterm{template-parameter}
are ignored when determining its type.

\pnum
\label{term.structural.type}%
A \defnadj{structural}{type} is one of the following:
\begin{itemize}
\item a scalar type, or
\item an lvalue reference type, or
\item a literal class type with the following properties:
\begin{itemize}
\item
all base classes and non-static data members are public and non-mutable and
\item
the types of all base classes and non-static data members are
structural types or (possibly multidimensional) arrays thereof.
\end{itemize}
\end{itemize}

\pnum
Certain constructs refer to template parameter objects,
which are distinct objects with static storage duration and non-volatile const type.
No two such objects have template-argument-equivalent values\iref{temp.type}.
An \grammarterm{id-expression} naming
a constant template parameter of class type \tcode{T}
denotes the template parameter object of type \tcode{const T},
which is template-argument-equivalent to
the corresponding template argument
after it has been converted
to the type of the template parameter\iref{temp.arg.nontype}.
\begin{note}
There can be template parameter objects of array type\iref{meta.define.static},
but such an object is never denoted by an \grammarterm{id-expression}
that names a constant template parameter.
\end{note}
\begin{note}
If an \grammarterm{id-expression} names
a non-reference constant template parameter,
then it is a prvalue if it has non-class type.
Otherwise, if it is of class type \tcode{T},
it is an lvalue and has type \tcode{const T}\iref{expr.prim.id.unqual}.
\end{note}
\begin{example}
\begin{codeblock}
using X = int;
struct A {};
template<const X& x, int i, A a> void f() {
  i++;                          // error: change of template parameter value

  &x;                           // OK
  &i;                           // error: address of non-reference template parameter
  &a;                           // OK
  int& ri = i;                  // error: attempt to bind non-const reference to temporary
  const int& cri = i;           // OK, const reference binds to temporary
  const A& ra = a;              // OK, const reference binds to a template parameter object
}
\end{codeblock}
\end{example}

\pnum
\begin{note}
A constant template parameter
cannot be declared to have type \cv{} \keyword{void}.
\begin{example}
\begin{codeblock}
template<void v> class X;       // error
template<void* pv> class Y;     // OK
\end{codeblock}
\end{example}
\end{note}

\pnum
A constant template parameter
\indextext{array!template parameter of type}%
of type ``array of \tcode{T}'' or
\indextext{function!template parameter of type}%
of function type \tcode{T}
is adjusted to be of type ``pointer to \tcode{T}''.
\begin{example}
\begin{codeblock}
template<int* a>   struct R { @\commentellip@ };
template<int b[5]> struct S { @\commentellip@ };
int p;
R<&p> w;                        // OK
S<&p> x;                        // OK due to parameter adjustment
int v[5];
R<v> y;                         // OK due to implicit argument conversion
S<v> z;                         // OK due to both adjustment and conversion
\end{codeblock}
\end{example}

\pnum
A constant template parameter declared with a type that
contains a placeholder type with a \grammarterm{type-constraint}
introduces the immediately-declared constraint
of the \grammarterm{type-constraint}
for the invented type corresponding to the placeholder\iref{dcl.fct}.

\pnum
A \defnadj{default}{template argument} is
a template argument\iref{temp.arg} specified after \tcode{=}
in a \grammarterm{template-parameter}.
A default template argument shall not be specified for
a template parameter pack\iref{temp.variadic}.
A default template argument may be specified in a template declaration.
A default template argument shall not be specified in
the \grammarterm{template-parameter-list}{s}
of the definition of a member of a class template
that appears outside of the member's class.
A default template argument
shall not be specified in a friend class template declaration.
If a friend function template declaration $D$
specifies a default template argument,
that declaration shall be a definition and
there shall be no other declaration of the function template
which is reachable from $D$ or from which $D$ is reachable.

\pnum
The set of default template arguments
available for use is obtained by merging the default arguments
from all prior declarations of the template in the
same way default function arguments are\iref{dcl.fct.default}.
\begin{example}
\begin{codeblock}
template<class T1, class T2 = int> class A;
template<class T1 = int, class T2> class A;
\end{codeblock}
is equivalent to
\begin{codeblock}
template<class T1 = int, class T2 = int> class A;
\end{codeblock}
\end{example}

\pnum
If a \grammarterm{template-parameter}
of a class template, variable template, or alias template has
a default template argument,
each subsequent \grammarterm{template-parameter}
shall either have a default template argument supplied or
declare a template parameter pack.
If a \grammarterm{template-parameter} of
a primary class template, primary variable template, or alias template
declares a template parameter pack,
it shall be the last \grammarterm{template-parameter}.
If a \grammarterm{template-parameter} of a function template
declares a template parameter pack, it
shall not be followed by another \grammarterm{template-parameter}
unless that template parameter is deducible from the
parameter-type-list\iref{dcl.fct} of the function template or
has a default argument\iref{temp.deduct}.
A template parameter of a deduction guide template\iref{temp.deduct.guide}
that does not have a default argument shall be deducible
from the parameter-type-list of the deduction guide template.
\begin{example}
\begin{codeblock}
template<class T1 = int, class T2> class B;     // error

// \tcode{U} can be neither deduced from the parameter-type-list nor specified
template<class... T, class... U> void f() { }   // error
template<class... T, class U> void g() { }      // error
\end{codeblock}
\end{example}

\indextext{\idxcode{<}!template and}%
\pnum
When parsing a default template argument
for a constant template parameter,
the first non-nested \tcode{>} is taken as
the end of the \grammarterm{template-parameter-list}
rather than a greater-than operator.
\begin{example}
\begin{codeblock}
template<int i = 3 > 4 >        // syntax error
class X { @\commentellip@ };

template<int i = (3 > 4) >      // OK
class Y { @\commentellip@ };
\end{codeblock}
\end{example}

\pnum
A \grammarterm{template-parameter} of
a template \grammarterm{template-parameter}
is permitted to have a default template argument.
When such default arguments are specified,
they apply to the template \grammarterm{template-parameter}
in the scope of the template \grammarterm{template-parameter}.
\begin{example}
\begin{codeblock}
template <template <class TT = float> class T> struct A {
  inline void f();
  inline void g();
};
template <template <class TT> class T> void A<T>::f() {
  T<> t;            // error: \tcode{TT} has no default template argument
}
template <template <class TT = char> class T> void A<T>::g() {
  T<> t;            // OK, \tcode{T<char>}
}
\end{codeblock}
\end{example}
The associated constraints of a template template parameter
shall not contain a concept-dependent constraint\iref{temp.constr.concept}.
\begin{example}
\begin{codeblock}
template<
  template<typename> concept C,
  template<C> class TT  // error: \tcode{C} forms a concept-dependent constraint
>
struct A {};
\end{codeblock}
\end{example}

\rSec1[temp.names]{Names of template specializations}

\pnum
A template specialization\iref{temp.spec} can be referred to by a
\grammarterm{template-id}:

\begin{bnf}
\nontermdef{simple-template-id}\br
  template-name \terminal{<} \opt{template-argument-list} \terminal{>}
\end{bnf}

\begin{bnf}
\nontermdef{template-id}\br
  simple-template-id\br
  operator-function-id \terminal{<} \opt{template-argument-list} \terminal{>}\br
  literal-operator-id \terminal{<} \opt{template-argument-list} \terminal{>}
\end{bnf}

\begin{bnf}
\nontermdef{template-name}\br
  identifier
\end{bnf}

\begin{bnf}
\nontermdef{template-argument-list}\br
  template-argument \opt{\terminal{...}}\br
  template-argument-list \terminal{,} template-argument \opt{\terminal{...}}
\end{bnf}

\begin{bnf}
\nontermdef{template-argument}\br
  template-argument-name\br
  constant-expression\br
  type-id\br
  braced-init-list
\end{bnf}

\begin{bnf}
\nontermdef{template-argument-name}\br
  \opt{nested-name-specifier} identifier\br
  nested-name-specifier \terminal{template} identifier
\end{bnf}

\pnum
\indextext{component name}%
The component name of a
\grammarterm{simple-template-id},
\grammarterm{template-id}, or
\grammarterm{template-name}
is the first name in it.

\pnum
A \tcode{<} is interpreted as the delimiter of
a \grammarterm{template-argument-list}
if either
\begin{itemize}
\item
it follows a \grammarterm{splice-specifier} that either
\begin{itemize}
\item appears in a type-only context or
\item is preceded by \keyword{template} or \keyword{typename}, or
\end{itemize}
\item
it follows a name that is not a \grammarterm{conversion-function-id} and
\begin{itemize}
\item
that follows the keyword \keyword{template} or a \tcode{\~}
after a \grammarterm{nested-name-specifier} or
in a class member access expression, or
\item
for which name lookup finds the injected-class-name of a class template or
finds any declaration of a template, or
\item
that is an unqualified name
for which name lookup either finds one or more functions or finds nothing, or
\item
that is a terminal name
in a \grammarterm{using-declarator}\iref{namespace.udecl},
in a \grammarterm{declarator-id}\iref{dcl.meaning}, or
in a type-only context
other than a \grammarterm{nested-name-specifier}\iref{temp.res}.
\end{itemize}
\end{itemize}
\begin{note}
If the name is an \grammarterm{identifier},
it is then interpreted as a \grammarterm{template-name}.
The keyword \keyword{template} is used to indicate
that a dependent qualified name\iref{temp.dep.type} denotes a template
where an expression might appear.
\end{note}
\begin{example}
\begin{codeblock}
struct X {
  template<std::size_t> X* alloc();
  template<std::size_t> static X* adjust();
};
template<class T> void f(T* p) {
  T* p1 = p->alloc<200>();              // error: \tcode{<} means less than
  T* p2 = p->template alloc<200>();     // OK, \tcode{<} starts template argument list
  T::adjust<100>();                     // error: \tcode{<} means less than
  T::template adjust<100>();            // OK, \tcode{<} starts template argument list

  static constexpr std::meta::info r = ^^T::adjust;
  T* p3 = [:r:]<200>();                 // error: \tcode{<} means less than
  T* p4 = template [:r:]<200>();        // OK, \tcode{<} starts template argument list
}}
\end{codeblock}
\end{example}

\pnum
\indextext{\idxcode{<}!template and}%
When parsing a \grammarterm{template-argument-list},
the first non-nested
\tcode{>}
\begin{footnote}
A \tcode{>} that encloses the \grammarterm{type-id}
of a \keyword{dynamic_cast}, \keyword{static_cast}, \keyword{reinterpret_cast}
or \keyword{const_cast}, or which encloses the \grammarterm{template-argument}{s}
of a subsequent \grammarterm{template-id} or
\grammarterm{splice-specialization-specifier},
is considered nested for the purpose of this description.
\end{footnote}
is taken as the ending delimiter
rather than a greater-than operator.
Similarly, the first non-nested \tcode{>>} is treated as two
consecutive but distinct \tcode{>} tokens, the first of which is taken
as the end of the \grammarterm{template-argument-list} and completes
the \grammarterm{template-id} or \grammarterm{splice-specialization-specifier}.
\begin{note}
The second \tcode{>}
token produced by this replacement rule can terminate an enclosing
\grammarterm{template-id} or \grammarterm{splice-specialization-specifier}
construct or it can be part of a different construct (e.g., a cast).
\end{note}
\begin{example}
\begin{codeblock}
template<int i> class X { @\commentellip@ };

X< 1>2 > x1;                            // syntax error
X<(1>2)> x2;                            // OK

template<class T> class Y { @\commentellip@ };
Y<X<1>> x3;                             // OK, same as \tcode{Y<X<1> > x3;}
Y<X<6>>1>> x4;                          // syntax error
Y<X<(6>>1)>> x5;                        // OK
\end{codeblock}
\end{example}

\pnum
The keyword \keyword{template} shall not appear immediately after
a declarative \grammarterm{nested-name-specifier}\iref{expr.prim.id.qual}.

\pnum
The \grammarterm{constant-expression} of a \grammarterm{template-argument}
shall not be an unparenthesized \grammarterm{splice-expression}.
\begin{example}
\begin{codeblock}
template<int> struct S { };
constexpr int k = 5;
constexpr std::meta::info r = ^^k;
S<[:r:]> s1;                        // error: unparenthesized \grammarterm{splice-expression} used as template argument
S<([:r:])> s2;                      // OK
S<[:r:] + 1> s3;                    // OK
\end{codeblock}
\end{example}

\pnum
A name prefixed by the keyword
\keyword{template}
shall be followed by a template argument list or
refer to a class template or an alias template.
The latter case is deprecated\iref{depr.template.template}.
The keyword \keyword{template} shall not appear immediately
before a \tcode{\~} token (as to name a destructor).
\begin{note}
The keyword
\keyword{template}
cannot be applied to non-template members of class templates.
\end{note}
\begin{note}
As is the case with the
\keyword{typename}
prefix, the
\keyword{template}
prefix is well-formed
even when lookup for the name would already find a template.
\end{note}
\begin{example}
\begin{codeblock}
template <class T> struct A {
  void f(int);
  template <class U> void f(U);
};

template <class T> void f(T t) {
  A<T> a;
  a.template f<>(t);                    // OK, calls template
  a.template f(t);                      // error: not a \grammarterm{template-id}
}

template <class T> struct B {
  template <class T2> struct C { };
};

// deprecated: \tcode{T::C} is assumed to name a class template:
template <class T, template <class X> class TT = T::template C> struct D { };
D<B<int> > db;
\end{codeblock}
\end{example}

\pnum
The component names of a \grammarterm{template-argument-name} are
those of its \grammarterm{nested-name-specifier} (if any) and
its \grammarterm{identifier}.

\pnum
A \grammarterm{template-id} or \grammarterm{splice-specialization-specifier}
is \defnx{valid}{\idxgram{template-id}!valid} if
\begin{itemize}
\item
  there are at most as many arguments as there are parameters
  or a parameter is a template parameter pack\iref{temp.variadic},

\item
  there is an argument for each non-deducible non-pack parameter
  that does not have a default \grammarterm{template-argument},

\item
  each \grammarterm{template-argument} matches the corresponding
  template parameter\iref{temp.arg},

\item
  substitution of each template argument into the following
  template parameters (if any) succeeds, and

\item
  if the \grammarterm{template-id} or
  \grammarterm{splice-specialization-specifier} is non-dependent,
  the associated constraints are satisfied as specified in the next paragraph.
\end{itemize}
A \grammarterm{simple-template-id} or
\grammarterm{splice-specialization-specifier}
shall be valid unless its respective
\grammarterm{template-name} or \grammarterm{splice-specifier}
designates a function template\iref{temp.deduct}.
\begin{example}
\begin{codeblock}
template<class T, T::type n = 0> class X;
struct S {
  using type = int;
};
using T1 = X<S, int, int>;      // error: too many arguments
using T2 = X<>;                 // error: no default argument for first template parameter
using T3 = X<1>;                // error: value \tcode{1} does not match type-parameter
using T4 = X<int>;              // error: substitution failure for second template parameter
using T5 = X<S>;                // OK
\end{codeblock}
\end{example}

\pnum
When the \grammarterm{template-name}
of a \grammarterm{simple-template-id} or
the \grammarterm{splice-specifier}
of a \grammarterm{splice-specialization-specifier}
designates a constrained non-function template
or
a constrained template template parameter,
and
all \grammarterm{template-argument}{s}
in the \grammarterm{simple-template-id} or
\grammarterm{splice-specialization-specifier}
are non-dependent\iref{temp.dep.temp},
the associated constraints\iref{temp.constr.decl}
of the constrained template
shall be satisfied\iref{temp.constr.constr}.
\begin{example}
\begin{codeblock}
template<typename T> concept C1 = sizeof(T) != sizeof(int);

template<C1 T> struct S1 { };
template<C1 T> using Ptr = T*;

S1<int>* p;                         // error: constraints not satisfied
Ptr<int> p;                         // error: constraints not satisfied

template<typename T>
struct S2 { Ptr<int> x; };          // ill-formed, no diagnostic required

template<typename T>
struct S3 { Ptr<T> x; };            // OK, satisfaction is not required

S3<int> x;                          // error: constraints not satisfied

template<template<C1 T> class X>
struct S4 {
  X<int> x;                         // ill-formed, no diagnostic required
};

template<typename T> concept C2 = sizeof(T) == 1;

template<C2 T> struct S { };

template struct S<char[2]>;         // error: constraints not satisfied
template<> struct S<char[2]> { };   // error: constraints not satisfied
\end{codeblock}
\end{example}

\pnum
A \defn{concept-id} is a \grammarterm{simple-template-id}
where the \grammarterm{template-name} is a \grammarterm{concept-name}.
A concept-id is a prvalue of type \tcode{bool}, and
does not name a template specialization.
A concept-id evaluates to \tcode{true}
if the concept's
normalized \grammarterm{constraint-expression}\iref{temp.constr.decl}
is satisfied\iref{temp.constr.constr} by the specified template arguments and
\tcode{false} otherwise.
\begin{note}
Since a \grammarterm{constraint-expression} is an unevaluated operand,
a concept-id appearing in a \grammarterm{constraint-expression}
is not evaluated except as necessary
to determine whether the normalized constraints are satisfied.
\end{note}
\begin{example}
\begin{codeblock}
template<typename T> concept C = true;
static_assert(C<int>);      // OK
\end{codeblock}
\end{example}

\rSec1[temp.arg]{Template arguments}

\rSec2[temp.arg.general]{General}

\pnum
\indextext{argument!template}%
The type and form of each \grammarterm{template-argument} specified
in a \grammarterm{template-id} or
in a \grammarterm{splice-specialization-specifier}
shall match the type and form specified for the corresponding
parameter declared by the template in its
\grammarterm{template-parameter-list}.
When the parameter declared by the template is a template
parameter pack\iref{temp.variadic}, it will correspond to zero or more
\grammarterm{template-argument}{s}.
\begin{example}
\begin{codeblock}
template<class T> class Array {
  T* v;
  int sz;
public:
  explicit Array(int);
  T& operator[](int);
  T& elem(int i) { return v[i]; }
};

Array<int> v1(20);
typedef std::complex<double> dcomplex;  // \tcode{std::complex} is a standard library template
Array<dcomplex> v2(30);
Array<dcomplex> v3(40);

void bar() {
  v1[3] = 7;
  v2[3] = v3.elem(4) = dcomplex(7,8);
}
\end{codeblock}
\end{example}

\pnum
The template argument list of a \grammarterm{template-head} is
a template argument list in which the $n^\text{th}$ template argument
has the value of
the $n^\text{th}$ template parameter of the \grammarterm{template-head}.
If the $n^\text{th}$ template parameter is
a template parameter pack\iref{temp.variadic},
the $n^\text{th}$ template argument is a pack expansion
whose pattern is the name of the template parameter pack.

\pnum
If a \grammarterm{template-argument} $A$
matches the form \grammarterm{template-argument-name},
it is interpreted as such;
the \grammarterm{identifier} is looked up
and its meaning is determined as follows:
\begin{itemize}
\item
If lookup finds an injected-class-name\iref{temp.local}, then:
\begin{itemize}
\item
When $A$ is for a type template template parameter,
$A$ denotes the corresponding class template.
\item
Otherwise, it denotes a \grammarterm{type-name}.
\end{itemize}
\item
Otherwise, if lookup finds a template,
$A$ denotes that template.
\item
Otherwise, if lookup finds a type alias or a type,
$A$ denotes the underlying type and is interpreted as a \grammarterm{type-id}.
\item
Otherwise, $A$ is interpreted as an expression.
\end{itemize}

\pnum
In a
\grammarterm{template-argument},
an ambiguity between a
\grammarterm{type-id}
and an expression is resolved to a
\grammarterm{type-id},
regardless of the form of the corresponding
\grammarterm{template-parameter}.
\begin{footnote}
There is no such ambiguity in a default
\grammarterm{template-argument}
because the form of the
\grammarterm{template-parameter}
determines the allowable forms of the
\grammarterm{template-argument}.
\end{footnote}
\begin{example}
\begin{codeblock}
template<class T> void f();
template<int I> void f();

void g() {
  f<int()>();       // \tcode{int()} is a \grammarterm{type-id}: call the first \tcode{f()}
}
\end{codeblock}
\end{example}

\pnum
\begin{note}
Names used in a \grammarterm{template-argument}
are subject to access control where they appear.
Because a template parameter is not a class member,
no access control applies where the template parameter is used.
\end{note}
\begin{example}
\begin{codeblock}
template<class T> class X {
  static T t;
};

class Y {
private:
  struct S { @\commentellip@ };
  X<S> x;           // OK, \tcode{S} is accessible
                    // \tcode{X<Y::S>} has a static member of type \tcode{Y::S}
                    // OK, even though \tcode{Y::S} is private
};

X<Y::S> y;          // error: \tcode{S} not accessible
\end{codeblock}
\end{example}
For a template argument that is a class type or a class template,
the template definition has no special access rights
to the members of the template argument.
\begin{example}
\begin{codeblock}
template <template <class TT> class T> class A {
  typename T<int>::S s;
};

template <class U> class B {
private:
  struct S { @\commentellip@ };
};

A<B> b;             // error: \tcode{A} has no access to \tcode{B::S}
\end{codeblock}
\end{example}

\pnum
When template argument packs or default template arguments are used,
a \grammarterm{template-argument} list can be empty.
In that case the empty
\tcode{<>}
brackets shall still be used as the
\grammarterm{template-argument-list}.
\begin{example}
\begin{codeblock}
template<class T = char> class String;
String<>* p;                    // OK, \tcode{String<char>}
String* q;                      // syntax error
template<class ... Elements> class Tuple;
Tuple<>* t;                     // OK, \tcode{Elements} is empty
Tuple* u;                       // syntax error
\end{codeblock}
\end{example}

\pnum
An explicit destructor call\iref{class.dtor} for an object that has a type
that is a class template specialization may explicitly specify the
\grammarterm{template-argument}{s}.
\begin{example}
\begin{codeblock}
template<class T> struct A {
  ~A();
};
void f(A<int>* p, A<int>* q) {
  p->A<int>::~A();              // OK, destructor call
  q->A<int>::~A<int>();         // OK, destructor call
}
\end{codeblock}
\end{example}

\pnum
If the use of a template argument
gives rise to an ill-formed construct in the instantiation of a
template specialization, the program is ill-formed.

\pnum
When name lookup for the component name of a
\grammarterm{template-id}
finds an overload set, both non-template functions in the overload
set and function templates in the overload set for
which the
\grammarterm{template-argument}{s}
do not match the
\grammarterm{template-parameter}{s}
are ignored.
\begin{note}
If none of the function templates have matching
\grammarterm{template-parameter}{s},
the program is ill-formed.
\end{note}

\pnum
When a \grammarterm{simple-template-id} or
\grammarterm{splice-specialization-specifier}
does not designate a function,
a default \grammarterm{template-argument} is
implicitly instantiated\iref{temp.inst}
when the value of that default argument is needed.
\begin{example}
\begin{codeblock}
template<typename T, typename U = int> struct S { };
S<bool>* p;         // the type of \tcode{p} is \tcode{S<bool, int>*}
\end{codeblock}
The default argument for \tcode{U} is instantiated to form the type \tcode{S<bool, int>*}.
\end{example}

\pnum
A \grammarterm{template-argument} followed by an ellipsis is
a pack expansion\iref{temp.variadic}.

\rSec2[temp.arg.type]{Type template arguments}

\pnum
A
\grammarterm{template-argument}
for a type template parameter
shall be a
\grammarterm{type-id}.

\pnum
\begin{example}
\begin{codeblock}
template <class T> class X { };
template <class T> void f(T t) { }
struct { } unnamed_obj;

void f() {
  struct A { };
  enum { e1 };
  typedef struct { } B;
  B b;
  X<A> x1;          // OK
  X<A*> x2;         // OK
  X<B> x3;          // OK
  f(e1);            // OK
  f(unnamed_obj);   // OK
  f(b);             // OK
}
\end{codeblock}
\end{example}
\begin{note}
A template type argument can be an incomplete type\iref{term.incomplete.type}.
\end{note}

\rSec2[temp.arg.nontype]{Constant template arguments}

\pnum
A template argument $E$ for
a constant template parameter with declared type \tcode{T}
shall be such that the invented declaration
\begin{codeblock}
T x = @$E$@ ;
\end{codeblock}
satisfies the semantic constraints for the definition of
a \tcode{constexpr} variable with static storage duration\iref{dcl.constexpr}.
If \tcode{T} contains a placeholder type\iref{dcl.spec.auto}
or a placeholder for a deduced class type\iref{dcl.type.class.deduct},
the type of the parameter is deduced from the above declaration.
\begin{note}
$E$ is a \grammarterm{template-argument} or
(for a default template argument) an \grammarterm{initializer-clause}.
\end{note}
If the parameter type thus deduced is not permitted
for a constant template parameter\iref{temp.param},
the program is ill-formed.

\pnum
The value of a constant template parameter $P$
of (possibly deduced) type \tcode{T}
is determined from its template argument $A$ as follows.
If \tcode{T} is not a class type and
$A$ is not a \grammarterm{braced-init-list},
$A$ shall be a converted constant expression\iref{expr.const.const}
of type \tcode{T}; the value of $P$ is $A$ (as converted).

\pnum
Otherwise, a temporary variable
\begin{codeblock}
constexpr T v = @$A$@;
\end{codeblock}
is introduced.
The lifetime of \tcode{v} ends immediately after initializing it and
any template parameter object (see below).
For each such variable,
the \grammarterm{id-expression} \tcode{v}
is termed a \defn{candidate initializer}.

\pnum
If \tcode{T} is a class type,
a template parameter object\iref{temp.param} exists
that is constructed so as to be template-argument-equivalent to \tcode{v};
$P$ denotes that template parameter object.
$P$ is copy-initialized from an unspecified candidate initializer
that is template-argument-equivalent to \tcode{v}.
If, for the initialization from any candidate initializer,
\begin{itemize}
\item
the initialization would be ill-formed, or
\item
the full-expression of an invented \grammarterm{init-declarator}
for the initialization would not be a constant expression
when interpreted as a \grammarterm{constant-expression}\iref{expr.const.const}, or
\item
the initialization would cause $P$ to not be template-argument-equivalent\iref{temp.type} to \tcode{v},
\end{itemize}
the program is ill-formed.

\pnum
Otherwise, the value of $P$ is that of v.

\pnum
For a constant template parameter of reference or pointer type,
or for each non-static data member of reference or pointer type
in a constant template parameter of class type or subobject thereof,
the reference or pointer value shall not refer
or point to (respectively):
\begin{itemize}
\item a temporary object\iref{class.temporary},
\item a string literal object\iref{lex.string},
\item the result of a \tcode{typeid} expression\iref{expr.typeid},
\item a predefined \mname{func} variable\iref{dcl.fct.def.general}, or
\item a subobject\iref{intro.object} of one of the above.
\end{itemize}

\pnum
\begin{example}
\begin{codeblock}
template <int& r> class A{};
extern int x;
A<x> a;                 // OK
void f(int p) {
  constexpr int& r = p; // OK
  A<r> a;               // error: a static constexpr \tcode{int\&} variable cannot be initialized to refer to \tcode{p} here
}
\end{codeblock}
\end{example}

\pnum
\begin{example}
\begin{codeblock}
template<const int* pci> struct X { @\commentellip@ };
int ai[10];
X<ai> xi;                       // array to pointer and qualification conversions

struct Y { @\commentellip@ };
template<const Y& b> struct Z { @\commentellip@ };
Y y;
Z<y> z;                         // no conversion, but note extra cv-qualification

template<int (&pa)[5]> struct W { @\commentellip@ };
int b[5];
W<b> w;                         // no conversion

void f(char);
void f(int);

template<void (*pf)(int)> struct A { @\commentellip@ };

A<&f> a;                        // selects \tcode{f(int)}

template<auto n> struct B { @\commentellip@ };
B<5> b1;                        // OK, template parameter type is \tcode{int}
B<'a'> b2;                      // OK, template parameter type is \tcode{char}
B<2.5> b3;                      // OK, template parameter type is \tcode{double}
B<void(0)> b4;                  // error: template parameter type cannot be \keyword{void}

template<int i> struct C { /* ... */ };
C<{ 42 }> c1;   // OK

struct J1 {
  J1 *self = this;
};
B<J1{}> j1;     // error: initialization of template parameter object is not a constant expression

struct J2 {
  J2 *self = this;
  constexpr J2() {}
  constexpr J2(const J2&) {}
};
B<J2{}> j2;     // error: template parameter object not template-argument-equivalent to introduced temporary
\end{codeblock}
\end{example}

\pnum
\begin{note}
A \grammarterm{string-literal}\iref{lex.string} is
not an acceptable \grammarterm{template-argument}
for a constant template parameter of non-class type.
\begin{example}
\begin{codeblock}
template<class T, T p> class X {
  @\commentellip@
};

X<const char*, "Studebaker"> x; // error: string literal object as \grammarterm{template-argument}
X<const char*, "Knope" + 1> x2; // error: subobject of string literal object as \grammarterm{template-argument}

const char p[] = "Vivisectionist";
X<const char*, p> y;            // OK

struct A {
  constexpr A(const char*) {}
};

X<A, "Pyrophoricity"> z;        // OK, \grammarterm{string-literal} is a constructor argument to \tcode{A}
\end{codeblock}
\end{example}
\end{note}

\pnum
\begin{note}
A temporary object
is not an acceptable
\grammarterm{template-argument}
when the corresponding
template parameter
has reference type.
\begin{example}
\begin{codeblock}
template<const int& CRI> struct B { @\commentellip@ };

B<1> b1;                        // error: temporary would be required for template argument

int c = 1;
B<c> b2;                        // OK

struct X { int n; };
struct Y { const int &r; };
template<Y y> struct C { @\commentellip@ };
C<Y{X{1}.n}> c;                 // error: subobject of temporary object used to initialize
                                // reference member of template parameter
\end{codeblock}
\end{example}
\end{note}

\rSec2[temp.arg.template]{Template template arguments}

\pnum
A
\grammarterm{template-argument}
for a template
template parameter
shall be the name of a template.
For a \grammarterm{type-tt-parameter},
the name shall denote a class template, alias template, or
type template template parameter.
For a \grammarterm{variable-tt-parameter},
the name shall denote a variable template or
variable template template parameter.
For a \grammarterm{concept-tt-parameter},
the name shall denote a concept or
concept template parameter.
Only primary templates are considered when matching the template template
argument with the corresponding parameter; partial specializations are not
considered even if their parameter lists match that of the template template
parameter.

\pnum
Any partial specializations\iref{temp.spec.partial} associated with the
primary template are considered when a
specialization based on the template template parameter is instantiated.
If a specialization is not reachable from the point of instantiation,
and it would have been selected had it been reachable, the program is ill-formed,
no diagnostic required.
\begin{example}
\begin{codeblock}
template<class T> class A {     // primary template
  int x;
};
template<class T> class A<T*> { // partial specialization
  long x;
};
template<template<class U> class V> class C {
  V<int>  y;
  V<int*> z;
};
C<A> c;             // \tcode{V<int>} within \tcode{C<A>} uses the primary template, so \tcode{c.y.x} has type \tcode{int}
                    // \tcode{V<int*>} within \tcode{C<A>} uses the partial specialization, so \tcode{c.z.x} has type \tcode{long}
\end{codeblock}
\end{example}

\pnum
A template template parameter \tcode{P} and
a \grammarterm{template-argument} \tcode{A} are
\defnx{compatible}{compatible!template template parameter and template argument}
if
\begin{itemize}
\item
\tcode{A} denotes a class template or an alias template and
\tcode{P} is a type template template parameter,
\item
\tcode{A} denotes a variable template and
\tcode{P} is a variable template template parameter, or
\item
\tcode{A} denotes a concept and
\tcode{P} is a concept template parameter.
\end{itemize}

\pnum
A template \grammarterm{template-argument} \tcode{A} matches a template
template parameter \tcode{P} when
\tcode{A} and \tcode{P} are compatible and
\tcode{P} is at least as specialized as \tcode{A}, ignoring constraints
on \tcode{A} if \tcode{P} is unconstrained.
If \tcode{P} contains a template parameter pack, then \tcode{A} also matches \tcode{P}
if each of \tcode{A}'s template parameters
matches the corresponding template parameter declared in the
\grammarterm{template-head} of \tcode{P}.
Two template parameters match if they are of the same kind,
for constant template parameters, their types are
equivalent\iref{temp.over.link}, and for template template parameters,
each of their corresponding template parameters matches, recursively.
When \tcode{P}'s \grammarterm{template-head} contains a \grammarterm{template-parameter}
that declares a template parameter
pack\iref{temp.variadic}, the template parameter pack will match zero or more template
parameters or template parameter packs declared in the \grammarterm{template-head} of
\tcode{A} with the same type and form as the template parameter pack declared in \tcode{P}
(ignoring whether those template parameters are template parameter packs).

\begin{example}
\begin{codeblock}
template<class T> class A { @\commentellip@ };
template<class T, class U = T> class B { @\commentellip@ };
template<class ... Types> class C { @\commentellip@ };
template<auto n> class D { @\commentellip@ };
template<template<class> class P> class X { @\commentellip@ };
template<template<class ...> class Q> class Y { @\commentellip@ };
template<template<int> class R> class Z { @\commentellip@ };

X<A> xa;            // OK
X<B> xb;            // OK
X<C> xc;            // OK
Y<A> ya;            // OK
Y<B> yb;            // OK
Y<C> yc;            // OK
Z<D> zd;            // OK
\end{codeblock}
\end{example}
\begin{example}
\begin{codeblock}
template <class T> struct eval;

template <template <class, class...> class TT, class T1, class... Rest>
struct eval<TT<T1, Rest...>> { };

template <class T1> struct A;
template <class T1, class T2> struct B;
template <int N> struct C;
template <class T1, int N> struct D;
template <class T1, class T2, int N = 17> struct E;

eval<A<int>> eA;                // OK, matches partial specialization of \tcode{eval}
eval<B<int, float>> eB;         // OK, matches partial specialization of \tcode{eval}
eval<C<17>> eC;                 // error: \tcode{C} does not match \tcode{TT} in partial specialization
eval<D<int, 17>> eD;            // error: \tcode{D} does not match \tcode{TT} in partial specialization
eval<E<int, float>> eE;         // error: \tcode{E} does not match \tcode{TT} in partial specialization
\end{codeblock}
\end{example}
\begin{example}
\begin{codeblock}
template<typename T> concept C = requires (T t) { t.f(); };
template<typename T> concept D = C<T> && requires (T t) { t.g(); };

template<template<C> class P> struct S { };

template<C> struct X { };
template<D> struct Y { };
template<typename T> struct Z { };

S<X> s1;            // OK, \tcode{X} and \tcode{P} have equivalent constraints
S<Y> s2;            // error: \tcode{P} is not at least as specialized as \tcode{Y}
S<Z> s3;            // OK, \tcode{P} is at least as specialized as \tcode{Z}
\end{codeblock}
\end{example}

\pnum
A template template parameter \tcode{P} is
at least as specialized as a template \grammarterm{template-argument} \tcode{A}
if, given the following rewrite to two function templates,
the function template corresponding to \tcode{P}
is at least as specialized as
the function template corresponding to \tcode{A}
according to the partial ordering rules
for function templates\iref{temp.func.order}.
Given an invented class template \tcode{X}
with the \grammarterm{template-head} of \tcode{A} (including default arguments
and \grammarterm{requires-clause}, if any):

\begin{itemize}
\item
Each of the two function templates has the same template parameters
and \grammarterm{requires-clause} (if any),
respectively, as \tcode{P} or \tcode{A}.
\item
Each function template has a single function parameter
whose type is a specialization of \tcode{X}
with template arguments corresponding to the template parameters
from the respective function template where,
for each \grammarterm{template-parameter} \tcode{PP}
in the \grammarterm{template-head} of the function template,
a corresponding \grammarterm{template-argument} \tcode{AA} is formed.
If \tcode{PP} declares a template parameter pack,
then \tcode{AA} is the pack expansion \tcode{PP...}\iref{temp.variadic};
otherwise, \tcode{AA} is an \grammarterm{id-expression} denoting \tcode{PP}.
\end{itemize}
If the rewrite produces an invalid type,
then \tcode{P} is not at least as specialized as \tcode{A}.

\rSec1[temp.constr]{Template constraints}

\rSec2[temp.constr.general]{General}

\pnum
\begin{note}
Subclause \ref{temp.constr} defines the meaning of constraints on template arguments.
The abstract syntax and satisfaction rules are defined
in \ref{temp.constr.constr}.
Constraints are associated with declarations in \ref{temp.constr.decl}.
Declarations are partially ordered by their associated constraints\iref{temp.constr.order}.
\end{note}

\rSec2[temp.constr.constr]{Constraints}

\rSec3[temp.constr.constr.general]{General}

\indextext{satisfy|see{constraint, satisfaction}}%

\pnum
A \defn{constraint} is a sequence of logical operations and
operands that specifies requirements on template arguments.
The operands of a logical operation are constraints.
There are five different kinds of constraints:
\begin{itemize}
\item conjunctions\iref{temp.constr.op},
\item disjunctions\iref{temp.constr.op},
\item atomic constraints\iref{temp.constr.atomic},
\item concept-dependent constraints\iref{temp.constr.concept}, and
\item fold expanded constraints\iref{temp.constr.fold}.
\end{itemize}

\pnum
In order for a constrained template to be instantiated\iref{temp.spec},
its associated constraints\iref{temp.constr.decl}
shall be satisfied as described in the following subclauses.
\begin{note}
Forming the name of a specialization of
a class template,
a variable template, or
an alias template\iref{temp.names}
requires the satisfaction of its constraints.
Overload resolution\iref{over.match.viable}
requires the satisfaction of constraints
on functions and function templates.
\end{note}

\rSec3[temp.constr.op]{Logical operations}

\pnum
There are two binary logical operations on constraints: conjunction
and disjunction.
\begin{note}
These logical operations have no corresponding \Cpp{} syntax.
For the purpose of exposition, conjunction is spelled
using the symbol $\land$ and disjunction is spelled using the
symbol $\lor$.
The operands of these operations are called the left
and right operands. In the constraint $A \land B$,
$A$ is the left operand, and $B$ is the right operand.
\end{note}

\pnum
A \defn{conjunction} is a constraint taking two
operands.
To determine if a conjunction is
\defnx{satisfied}{constraint!satisfaction!conjunction},
the satisfaction of
the first operand is checked.
If that is not satisfied, the conjunction is not satisfied.
Otherwise, the conjunction is satisfied if and only if the second
operand is satisfied.

\pnum
A \defn{disjunction} is a constraint taking two
operands.
%
To determine if a disjunction is
\defnx{satisfied}{constraint!satisfaction!disjunction},
the satisfaction of
the first operand is checked.
If that is satisfied, the disjunction is satisfied.
Otherwise, the disjunction is satisfied if and only if the second
operand is satisfied.

\pnum
\begin{example}
\begin{codeblock}
template<typename T>
  constexpr bool get_value() { return T::value; }

template<typename T>
  requires (sizeof(T) > 1) && (get_value<T>())
    void f(T);      // has associated constraint \tcode{sizeof(T) > 1 $\land$ get_value<T>()}

void f(int);

f('a'); // OK, calls \tcode{f(int)}
\end{codeblock}
In the satisfaction of the associated constraints\iref{temp.constr.decl}
of \tcode{f}, the constraint \tcode{sizeof(char) > 1} is not satisfied;
the second operand is not checked for satisfaction.
\end{example}

\pnum
\begin{note}
A logical negation expression\iref{expr.unary.op} is an atomic constraint;
the negation operator is not treated as a logical operation on constraints.
As a result, distinct negation \grammarterm{constraint-expression}{s}
that are equivalent under~\ref{temp.over.link}
do not subsume one another under~\ref{temp.constr.order}.
Furthermore, if substitution to determine
whether an atomic constraint is satisfied\iref{temp.constr.atomic}
encounters a substitution failure, the constraint is not satisfied,
regardless of the presence of a negation operator.
\begin{example}
\begin{codeblock}
template <class T> concept sad = false;

template <class T> int f1(T) requires (!sad<T>);
template <class T> int f1(T) requires (!sad<T>) && true;
int i1 = f1(42);        // ambiguous, \tcode{!sad<T>} atomic constraint expressions\iref{temp.constr.atomic}
                        // are not formed from the same \grammarterm{expression}

template <class T> concept not_sad = !sad<T>;
template <class T> int f2(T) requires not_sad<T>;
template <class T> int f2(T) requires not_sad<T> && true;
int i2 = f2(42);        // OK, \tcode{!sad<T>} atomic constraint expressions both come from \tcode{not_sad}

template <class T> int f3(T) requires (!sad<typename T::type>);
int i3 = f3(42);        // error: associated constraints not satisfied due to substitution failure

template <class T> concept sad_nested_type = sad<typename T::type>;
template <class T> int f4(T) requires (!sad_nested_type<T>);
int i4 = f4(42);        // OK, substitution failure contained within \tcode{sad_nested_type}
\end{codeblock}
Here,
\tcode{requires (!sad<typename T::type>)} requires
that there is a nested \tcode{type} that is not \tcode{sad},
whereas
\tcode{requires (!sad_nested_type<T>)} requires
that there is no \tcode{sad} nested \tcode{type}.
\end{example}
\end{note}

\rSec3[temp.constr.atomic]{Atomic constraints}

\pnum
An \defnadj{atomic}{constraint} is formed from
an expression \tcode{E}
and a mapping from the template parameters
that appear within \tcode{E} to
template arguments that are formed via substitution during constraint normalization
in the declaration of a constrained entity (and, therefore, can involve the
unsubstituted template parameters of the constrained entity),
called the \defn{parameter mapping}\iref{temp.constr.decl}.
\begin{note}
Atomic constraints are formed by constraint normalization\iref{temp.constr.normal}.
\tcode{E} is never a logical \logop{and} expression\iref{expr.log.and}
nor a logical \logop{or} expression\iref{expr.log.or}.
\end{note}

\pnum
Two atomic constraints, $e_1$ and $e_2$, are
\indextext{identical!atomic constraints|see{atomic constraint, identical}}%
\defnx{identical}{atomic constraint!identical}
if they are formed from the same appearance of the same
\grammarterm{expression}
and if, given a hypothetical template $A$
whose \grammarterm{template-parameter-list} consists of
\grammarterm{template-parameter}s corresponding and equivalent\iref{temp.over.link} to
those mapped by the parameter mappings of the expression,
a \grammarterm{template-id} naming $A$
whose \grammarterm{template-argument}s are
the targets of the parameter mapping of $e_1$
is the same\iref{temp.type} as
a \grammarterm{template-id} naming $A$
whose \grammarterm{template-argument}s are
the targets of the parameter mapping of $e_2$.
\begin{note}
The comparison of parameter mappings of atomic constraints
operates in a manner similar to that of declaration matching
with alias template substitution\iref{temp.alias}.
\begin{example}
\begin{codeblock}
template <unsigned N> constexpr bool Atomic = true;
template <unsigned N> concept C = Atomic<N>;
template <unsigned N> concept Add1 = C<N + 1>;
template <unsigned N> concept AddOne = C<N + 1>;
template <unsigned M> void f()
  requires Add1<2 * M>;
template <unsigned M> int f()
  requires AddOne<2 * M> && true;

int x = f<0>();     // OK, the atomic constraints from concept \tcode{C} in both \tcode{f}s are \tcode{Atomic<N>}
                    // with mapping similar to $\tcode{N} \mapsto \tcode{2 * M + 1}$

template <unsigned N> struct WrapN;
template <unsigned N> using Add1Ty = WrapN<N + 1>;
template <unsigned N> using AddOneTy = WrapN<N + 1>;
template <unsigned M> void g(Add1Ty<2 * M> *);
template <unsigned M> void g(AddOneTy<2 * M> *);

void h() {
  g<0>(nullptr);    // OK, there is only one \tcode{g}
}
\end{codeblock}
\end{example}
As specified in \ref{temp.over.link},
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.
\begin{example}
\begin{codeblock}
template <unsigned N> void f2()
  requires Add1<2 * N>;
template <unsigned N> int f2()
  requires Add1<N * 2> && true;
void h2() {
  f2<0>();          // ill-formed, no diagnostic required:
                    // requires determination of subsumption between atomic constraints that are
                    // functionally equivalent but not equivalent
}
\end{codeblock}
\end{example}
\end{note}

\pnum
To determine if an atomic constraint is
\defnx{satisfied}{constraint!satisfaction!atomic},
the parameter mapping and template arguments are
first substituted into its expression.
If substitution results in an invalid type or expression
in the immediate context of the atomic constraint\iref{temp.deduct.general},
the constraint is not satisfied.
Otherwise, the lvalue-to-rvalue conversion\iref{conv.lval}
is performed if necessary,
and \tcode{E} shall be a constant expression of type \tcode{bool}.
The constraint is satisfied if and only if evaluation of \tcode{E}
results in \tcode{true}.
If, at different points in the program, the satisfaction result is different
for identical atomic constraints and template arguments,
the program is ill-formed, no diagnostic required.
\begin{example}
\begin{codeblock}
template<typename T> concept C =
  sizeof(T) == 4 && !true;      // requires atomic constraints \tcode{sizeof(T) == 4} and \tcode{!true}

template<typename T> struct S {
  constexpr operator bool() const { return true; }
};

template<typename T> requires (S<T>{})
void f(T);                      // \#1
void f(int);                    // \#2

void g() {
  f(0);                         // error: expression \tcode{S<int>\{\}} does not have type \tcode{bool}
}                               // while checking satisfaction of deduced arguments of \#1;
                                // call is ill-formed even though \#2 is a better match
\end{codeblock}
\end{example}

\rSec3[temp.constr.concept]{Concept-dependent constraints}

\pnum
A \defnadj{concept-dependent}{constraint} \tcode{CD} is
an atomic constraint whose expression is a concept-id \tcode{CI} whose
\grammarterm{concept-name} names a dependent concept named \tcode{C}.

\pnum
To determine if \tcode{CD} is
\defnx{satisfied}{constraint!satisfaction!concept-dependent},
the parameter mapping and template arguments are first
substituted into \tcode{C}.
If substitution results in an invalid concept-id in
the immediate context of the constraint\iref{temp.deduct.general},
the constraint is not satisfied.
Otherwise, let \tcode{CI$'$} be
the normal form\iref{temp.constr.normal} of the concept-id
after substitution of \tcode{C}.
\begin{note}
Normalization of \tcode{CI} can be ill-formed with no diagnostic required.
\end{note}

\pnum
To form \tcode{CI$''$},
each appearance of \tcode{C}{'s} template parameters in
the parameter mappings of the atomic constraints
(including concept-dependent constraints)
in \tcode{CI$'$}
is substituted with their respective arguments from
the parameter mapping of \tcode{CD} and the arguments of \tcode{CI}.

\pnum
\tcode{CD} is satisfied if \tcode{CI$''$} is satisfied.
\begin{note}
Checking whether \tcode{CI$''$} is satisfied
can lead to further normalization of concept-dependent constraints.
\end{note}
\begin{example}
\begin{codeblock}
template<typename>
concept C = true;

template<typename T, template<typename> concept CC>
concept D = CC<T>;

template<typename U,
         template<typename> concept CT,
         template<typename, template<typename> concept> concept CU>
int f() requires CU<U, CT>;
int i = f<int, C, D>();
\end{codeblock}
In this example, the associated constraints of \tcode{f}
consist of a concept-dependent constraint
whose expression is the concept-id \tcode{CU<U, CT>} with the mapping
$\tcode{U} \mapsto \tcode{U}, \tcode{CT} \mapsto \tcode{CT}, \tcode{CU} \mapsto \tcode{CU}$.
The result of substituting \tcode{D} into this expression is \tcode{D<U, CT>}.
We consider the normal form of the resulting concept-id,
which is \tcode{CC<T>} with the mapping
$\tcode{T} \mapsto \tcode{U}, \tcode{CC} \mapsto \tcode{CT}$.
By recursion, \tcode{C} is substituted into \tcode{CC<T>}, and the result
is normalized to the atomic constraint \tcode{true}, which is satisfied.
\end{example}

\rSec3[temp.constr.fold]{Fold expanded constraint}

\pnum
A \defnadj{fold expanded}{constraint} is formed from a constraint $C$ and
a \grammarterm{fold-operator}
which can either be \tcode{\&\&} or \tcode{||}.
A fold expanded constraint is a pack expansion\iref{temp.variadic}.
Let $N$ be the number of elements
in the pack expansion parameters\iref{temp.variadic}.

\pnum
A fold expanded constraint whose \grammarterm{fold-operator} is \tcode{\&\&}
is satisfied if it is a valid pack expansion and
if $N = 0$ or if for each $i$ where $0 \le i < N$ in increasing order,
$C$ is satisfied
when replacing each pack expansion parameter
with the corresponding $i^\text{th}$ element.
No substitution takes place for any $i$ greater than
the smallest $i$ for which the constraint is not satisfied.

\pnum
A fold expanded constraint whose \grammarterm{fold-operator} is \tcode{||}
is satisfied if it is a valid pack expansion,
$N > 0$, and if for $i$ where $0 \le i < N$ in increasing order,
there is a smallest $i$ for which $C$ is satisfied
when replacing each pack expansion parameter
with the corresponding $i^\text{th}$ element.
No substitution takes place for any $i$ greater than
the smallest $i$ for which the constraint is satisfied.

\pnum
\begin{note}
If the pack expansion expands packs of different size,
then it is invalid and the fold expanded constraint is not satisfied.
\end{note}

\pnum
Two fold expanded constraints are \defnadj{compatible for}{subsumption}
if their respective constraints both contain
an equivalent unexpanded pack\iref{temp.over.link}.

\rSec2[temp.constr.decl]{Constrained declarations}

\pnum
A template declaration\iref{temp.pre}
or templated function declaration\iref{dcl.fct}
can be constrained by the use of a \grammarterm{requires-clause}.
This allows the specification of constraints for that declaration as
an expression:

\begin{bnf}
\nontermdef{constraint-expression}\br
    logical-or-expression
\end{bnf}

\pnum
Constraints can also be associated with a declaration through the use of
\grammarterm{type-constraint}{s}
in a \grammarterm{template-parameter-list} or parameter-type-list.
Each of these forms introduces additional \grammarterm{constraint-expression}{s}
that are used to constrain the declaration.

\pnum
\indextext{constraint!associated|see{associated constraints}}%
A declaration's \defn{associated constraints} are defined as follows:

\begin{itemize}
\item If there are no introduced \grammarterm{constraint-expression}{s},
the declaration has no associated constraints.

\item Otherwise, if there is a single introduced \grammarterm{constraint-expression},
the associated constraints are the normal form\iref{temp.constr.normal}
of that expression.

\item Otherwise, the associated constraints are the normal form of a logical
\logop{and} expression\iref{expr.log.and} whose operands are in the
following order:
\begin{itemize}
\item
the \grammarterm{constraint-expression} introduced by
each \grammarterm{type-constraint}\iref{temp.param} in
the declaration's \grammarterm{template-parameter-list},
in order of appearance, and

\item
the \grammarterm{constraint-expression} introduced by
a \grammarterm{requires-clause} following
a \grammarterm{template-parameter-list}\iref{temp.pre}, and

\item
the \grammarterm{constraint-expression} introduced by
each \grammarterm{type-constraint} in
the parameter-type-list of a function declaration, and

\item
the \grammarterm{constraint-expression} introduced by
a trailing \grammarterm{requires-clause}\iref{dcl.decl} of
a function declaration\iref{dcl.fct}.
\end{itemize}
\end{itemize}

The formation of the associated constraints
establishes the order in which constraints are instantiated when checking
for satisfaction\iref{temp.constr.constr}.
\begin{example}
\begin{codeblock}
template<typename T> concept C = true;

template<C T> void f1(T);
template<typename T> requires C<T> void f2(T);
template<typename T> void f3(T) requires C<T>;
\end{codeblock}
The functions \tcode{f1}, \tcode{f2}, and \tcode{f3} have the associated
constraint \tcode{C<T>}.

\begin{codeblock}
template<typename T> concept C1 = true;
template<typename T> concept C2 = sizeof(T) > 0;

template<C1 T> void f4(T) requires C2<T>;
template<typename T> requires C1<T> && C2<T> void f5(T);
\end{codeblock}
The associated constraints of \tcode{f4} and \tcode{f5}
are \tcode{C1<T> $\land$ C2<T>}.

\begin{codeblock}
template<C1 T> requires C2<T> void f6();
template<C2 T> requires C1<T> void f7();
\end{codeblock}
The associated constraints of
\tcode{f6} are \tcode{C1<T> $\land$ C2<T>},
and those of
\tcode{f7} are \tcode{C2<T> $\land$ C1<T>}.
\end{example}

\pnum
When determining whether a given introduced
\grammarterm{constraint-expression} $C_1$ of a declaration
in an instantiated specialization of a templated class
is equivalent\iref{temp.over.link} to the corresponding
\grammarterm{constraint-expression} $C_2$ of a declaration
outside the class body,
$C_1$ is instantiated.
If the instantiation results in an invalid expression,
the \grammarterm{constraint-expression}s are not equivalent.
\begin{note}
This can happen when determining which member template is specialized
by an explicit specialization declaration.
\end{note}
\begin{example}
\begin{codeblock}
template <class T> concept C = true;
template <class T> struct A {
  template <class U> U f(U) requires C<typename T::type>;   // \#1
  template <class U> U f(U) requires C<T>;                  // \#2
};

template <> template <class U>
U A<int>::f(U u) requires C<int> { return u; }              // OK, specializes \#2
\end{codeblock}
Substituting \tcode{int} for \tcode{T} in \tcode{C<typename T::type>}
produces an invalid expression, so the specialization does not match \#1.
Substituting \tcode{int} for \tcode{T} in \tcode{C<T>} produces \tcode{C<int>},
which is equivalent to the \grammarterm{constraint-expression} for the specialization,
so it does match \#2.
\end{example}

\rSec2[temp.constr.normal]{Constraint normalization}
\indextext{constraint!normalization|(}%

\pnum
The \defnx{normal form}{normal form!constraint} of an \grammarterm{expression} \tcode{E} is
a constraint\iref{temp.constr.constr} that is defined as follows:
%
\begin{itemize}
\item
The normal form of an expression \tcode{( E )} is
the normal form of \tcode{E}.

\item
The normal form of an expression \tcode{E1 || E2} is
the disjunction\iref{temp.constr.op} of
the normal forms of \tcode{E1} and \tcode{E2}.

\item
The normal form of an expression \tcode{E1 \&\& E2}
is the conjunction of
the normal forms of \tcode{E1} and \tcode{E2}.

\item
For a concept-id \tcode{C<A$_1$, A$_2$, $\dotsc$, A$_n$>} termed \tcode{CI}:
\begin{itemize}
\item
If \tcode{C} names a dependent concept,
the normal form of \tcode{CI} is a concept-dependent constraint
whose concept-id is \tcode{CI} and
whose parameter mapping is the identity mapping.
\item
Otherwise, to form \tcode{CE},
%FIXME: We're saying any Ai can be used to form CE. Do we have to try all
%FIXME: the Ais to check for ill-formedness or just the random one we picked?
%FIXME: Don't we want to form a CEi for each Ai?
any non-dependent concept template argument \tcode{A$_i$}
is substituted into the \grammarterm{constraint-expression} of \tcode{C}.
If any such substitution results in an invalid concept-id,
the program is ill-formed; no diagnostic is required.
The normal form of \tcode{CI} is the result of substituting,
in the normal form \tcode{N} of \tcode{CE},
appearances of \tcode{C}{'s} template parameters
in the parameter mappings of the atomic constraints in \tcode{N}
with their respective arguments from \tcode{C}.
If any such substitution results in an invalid type or expression,
the program is ill-formed; no diagnostic is required.
\end{itemize}
\begin{example}
\begin{codeblock}
template<typename T> concept A = T::value || true;
template<typename U> concept B = A<U*>;
template<typename V> concept C = B<V&>;
\end{codeblock}
Normalization of \tcode{B}{'s} \grammarterm{constraint-expression}
is valid and results in
\tcode{T::value} (with the mapping $\tcode{T} \mapsto \tcode{U*}$)
$\lor$
\tcode{true} (with an empty mapping),
despite the expression \tcode{T::value} being ill-formed
for a pointer type \tcode{T}.
Normalization of \tcode{C}{'s} \grammarterm{constraint-expression}
results in the program being ill-formed,
because it would form the invalid type \tcode{V\&*}
in the parameter mapping.
\end{example}

\item
For a \grammarterm{fold-operator} \tcode{Op}\iref{expr.prim.fold}
that is either \tcode{\&\&} or \tcode{||}:
  \begin{itemize}
  \item
  The normal form of an expression \tcode{( ... Op E )}
  is the normal form of \tcode{( E Op ... )}.
  \item
  The normal form of an expression \tcode{( E1 Op ... Op E2 )}
  is the normal form of
    \begin{itemize}
    \item
    \tcode{( E1 Op ... ) Op E2} if \tcode{E1} contains an unexpanded pack, or
    \item
    \tcode{E1 Op ( E2 Op ... )} otherwise.
    \end{itemize}
  \item
  The normal form of an expression \tcode{F} of the form \tcode{( E Op ... )}
  is as follows:\\
  If \tcode{E} contains an unexpanded concept template parameter pack,
  it shall not contain an unexpanded template parameter pack of another kind.
  Let \tcode{E$'$} be the normal form of \tcode{E}.
    \begin{itemize}
    \item
    If \tcode{E} contains
    an unexpanded concept template parameter pack \tcode{P$_k$} that
    has corresponding template arguments in
    the parameter mapping of any atomic constraint
    (including concept-dependent constraints) of \tcode{E$'$},
    the number of arguments specified for all such \tcode{P$_k$}
    shall be the same number $N$.
    The normal form of \tcode{F} is the normal form of
    \tcode{E$_0$ Op $\dotsb$ Op E$_{N-1}$}
    after substituting in \tcode{E$_i$}
    the respective $i^\text{th}$ concept argument of each \tcode{P$_k$}.
    If any such substitution results in an invalid type or expression,
    the program is ill-formed; no diagnostic is required.
    \item
    Otherwise,
    the normal form of \tcode{F} is
    a fold expanded constraint\iref{temp.constr.fold} whose
    constraint is \tcode{E$'$} and whose
    \grammarterm{fold-operator} is \tcode{Op}.
    \end{itemize}
  \end{itemize}

\item
The normal form of any other expression \tcode{E} is
the atomic constraint
whose expression is \tcode{E} and
whose parameter mapping is the identity mapping.
\end{itemize}

\pnum
The process of obtaining the normal form of a
\grammarterm{constraint-expression}
is called
\defnx{normalization}{normalization!constraint|see{constraint, normalization}}.
\begin{note}
Normalization of \grammarterm{constraint-expression}{s}
is performed
when determining the associated constraints\iref{temp.constr.constr}
of a declaration
and
when evaluating the value of an \grammarterm{id-expression}
that names a concept specialization\iref{expr.prim.id}.
\end{note}

\pnum
\begin{example}
\begin{codeblock}
template<typename T> concept C1 = sizeof(T) == 1;
template<typename T> concept C2 = C1<T> && 1 == 2;
template<typename T> concept C3 = requires { typename T::type; };
template<typename T> concept C4 = requires (T x) { ++x; };

template<C2 U> void f1(U);      // \#1
template<C3 U> void f2(U);      // \#2
template<C4 U> void f3(U);      // \#3
\end{codeblock}
The associated constraints of \#1 are
\tcode{sizeof(T) == 1} (with mapping $\tcode{T} \mapsto \tcode{U}$) $\land$ \tcode{1 == 2}.\\
The associated constraints of \#2 are
\tcode{requires \{ typename T::type; \}} (with mapping $\tcode{T} \mapsto \tcode{U}$).\\
The associated constraints of \#3 are
\tcode{requires (T x) \{ ++x; \}} (with mapping $\tcode{T} \mapsto \tcode{U}$).
\end{example}

\begin{example}
\begin{codeblock}
template<typename T>
concept C = true;
template<typename T, template<typename> concept CT>
concept CC = CT<T>;

template<typename U,
         template<typename, template<typename> concept> concept CT>
  void f() requires CT<U*, C>;
template<typename U>
  void g() requires CC<U*, C>;
\end{codeblock}
The normal form of the associated constraints of \tcode{f} is
the concept-dependent constraint \tcode{CT<T, C>}.\\
The normal form of the associated constraints of \tcode{g} is
the atomic constraint \tcode{true}.
\end{example}

\begin{example}
\begin{codeblock}
template<typename T>
concept A = true;
template<typename T>
concept B = A<T> && true;                               // \tcode{B} subsumes \tcode{A}
template<typename T>
concept C = true;
template<typename T>
concept D = C<T> && true;                               // \tcode{D} subsumes \tcode{C}

template<typename T, template<typename> concept... CTs>
concept all_of = (CTs<T> && ...);

template<typename T> requires all_of<T, A, C>
  constexpr int f(T) { return 1; }                      // \#1
template<typename T> requires all_of<T, B, D>
  constexpr int f(T) { return 2; }                      // \#2

static_assert(f(1) == 2);                               // ok
\end{codeblock}
The normal form of \tcode{all_of<T, A, C>} is
the conjunction of the normal forms of \tcode{A<T>} and \tcode{C<T>}.\\
Similarly, the normal form of \tcode{all_of<T, B, D>} is
the conjunction of the normal forms of \tcode{B<T>} and \tcode{D<T>}.\\
\#2 therefore is more constrained than \#1.
\end{example}

\begin{example}
\begin{codeblock}
template<typename T, template<typename> concept>
struct wrapper {};

template<typename... T, template<typename> concept... CTs>
  int f(wrapper<T, CTs>...) requires (CTs<T> && ...);   // error: fold expression contains
                                                        // different kinds of template parameters
\end{codeblock}
\end{example}

\indextext{constraint!normalization|)}

\rSec2[temp.constr.order]{Partial ordering by constraints}

\pnum
\indextext{subsume|see{constraint, subsumption}}
A constraint $P$ \defnx{subsumes}{constraint!subsumption} a constraint $Q$
if and only if,
for every disjunctive clause $P_i$
in the disjunctive normal form
\begin{footnote}
A constraint is in disjunctive normal form when it is a disjunction of
clauses where each clause is a conjunction of fold expanded or atomic constraints.
For atomic constraints $A$, $B$, and $C$, the disjunctive normal form
of the constraint
$A \land (B \lor C)$
is
$(A \land B) \lor (A \land C)$.
%
Its disjunctive clauses are $(A \land B)$ and $(A \land C)$.
\end{footnote}
of $P$, $P_i$ subsumes every conjunctive clause $Q_j$
in the conjunctive normal form
\begin{footnote}
A constraint is in conjunctive normal form when it is a conjunction
of clauses where each clause is a disjunction of fold expanded or atomic constraints.
For atomic constraints $A$, $B$, and $C$, the constraint
$A \land (B \lor C)$ is in conjunctive normal form.
%
Its conjunctive clauses are $A$ and $(B \lor C)$.
\end{footnote}
of $Q$, where
\begin{itemize}
\item
a disjunctive clause $P_i$ subsumes a conjunctive clause $Q_j$ if and only
if there exists an atomic constraint $P_{ia}$ in $P_i$ for which there exists
an atomic constraint $Q_{jb}$ in $Q_j$ such that $P_{ia}$ subsumes $Q_{jb}$,

\item an atomic constraint $A$ subsumes another atomic constraint
$B$ if and only if $A$ and $B$ are identical using the
rules described in \ref{temp.constr.atomic}, and

\item a fold expanded constraint $A$ subsumes
another fold expanded constraint $B$
if they are compatible for subsumption,
have the same \grammarterm{fold-operator}, and
the constraint of $A$ subsumes that of $B$.
\end{itemize}
%
\begin{example}
Let $A$ and $B$ be atomic constraints\iref{temp.constr.atomic}.
%
The constraint $A \land B$ subsumes $A$, but $A$ does not subsume $A \land B$.
%
The constraint $A$ subsumes $A \lor B$, but $A \lor B$ does not subsume $A$.
%
Also note that every constraint subsumes itself.
\end{example}

\pnum
\begin{note}
The subsumption relation defines a partial ordering on constraints.
This partial ordering is used to determine
\begin{itemize}
\item the best viable candidate of non-template functions\iref{over.match.best},
\item the address of a non-template function\iref{over.over},
\item the matching of template template arguments\iref{temp.arg.template},
\item the partial ordering of class template specializations\iref{temp.spec.partial.order}, and
\item the partial ordering of function templates\iref{temp.func.order}.
\end{itemize}
\end{note}

\pnum
The associated constraints \tcode{C} of a declaration \tcode{D}
\indextext{subsumption!eligible for}%
are \defnx{eligible for subsumption}{eligible!for subsumption}
%%% FIXME: This "definiton" needs work. Do we mean:
%%% "if C can be subsumed and C does not contain a concept-dependent constraint"?
unless \tcode{C} contains a concept-dependent constraint.

%%% FIXME: We need to substitute the deductions from partial ordering
%%% into the constraints before comparing them, otherwise they will be
%%% referring to unrelated template parameters.
\pnum
A declaration \tcode{D1} is
\defn{at least as constrained} as
a declaration \tcode{D2} if
\begin{itemize}
\item \tcode{D1} and \tcode{D2} are both constrained declarations and
\tcode{D1}'s associated constraints
are eligible for subsumption and subsume those of \tcode{D2}; or

\item \tcode{D2} has no associated constraints.
\end{itemize}

\pnum
A declaration \tcode{D1} is \defn{more constrained}
than another declaration \tcode{D2} when \tcode{D1} is at least as
constrained as \tcode{D2}, and \tcode{D2} is not at least as
constrained as \tcode{D1}.
\begin{example}
\begin{codeblock}
template<typename T> concept C1 = requires(T t) { --t; };
template<typename T> concept C2 = C1<T> && requires(T t) { *t; };

template<C1 T> void f(T);       // \#1
template<C2 T> void f(T);       // \#2
template<typename T> void g(T); // \#3
template<C1 T> void g(T);       // \#4

f(0);                           // selects \#1
f((int*)0);                     // selects \#2
g(true);                        // selects \#3 because \tcode{C1<bool>} is not satisfied
g(0);                           // selects \#4
\end{codeblock}
\end{example}
\begin{example}
\begin{codeblock}
template<template<typename T> concept CT, typename T>
struct S {};
template<typename T>
concept A = true;

template<template<typename T> concept X, typename T>
int f(S<X, T>) requires A<T> { return 42; }             // \#1
template<template<typename T> concept X, typename T>
int f(S<X, T>) requires X<T> { return 43; }             // \#2

f(S<A, int>{});                 // ok, select \#1 because \#2 is not eligible for subsumption
\end{codeblock}
\end{example}

\pnum
A non-template function \tcode{F1} is \defn{more partial-ordering-constrained}
than a non-template function \tcode{F2} if
\begin{itemize}
\item
they have the same non-object-parameter-type-lists\iref{dcl.fct}, and
\item
if they are member functions, both are direct members of the same class, and
\item
if both are non-static member functions,
they have the same types for their object parameters, and
\item
the declaration of \tcode{F1} is more constrained than
the declaration of \tcode{F2}.
\end{itemize}

\rSec1[temp.type]{Type equivalence}

\pnum
\indextext{equivalence!template type}%
Two \grammarterm{template-id}{s} are the same if
\begin{itemize}
\item
their \grammarterm{template-name}{s},
\grammarterm{operator-function-id}{s}, or
\grammarterm{literal-operator-id}{s}
refer to the same template, and

\item
their corresponding type \grammarterm{template-argument}{s}
are the same type, and

\item
the template parameter values determined by
their corresponding constant template arguments\iref{temp.arg.nontype}
are template-argument-equivalent (see below), and

\item
their corresponding template \grammarterm{template-argument}{s}
refer to the same template.
\end{itemize}
Two \grammarterm{template-id}{s} that are the same
refer to the same class, function, or variable.

\pnum
Two values are \defn{template-argument-equivalent} if
they are of the same type and
\begin{itemize}
\item
they are of integral type and their values are the same, or

\item
they are of floating-point type and their values are identical, or

\item
they are of type \tcode{std::nullptr_t}, or

\item
they are of type \tcode{std::meta::info} and
their values compare equal\iref{expr.eq}, or

\item
they are of enumeration type and their values are the same,
\begin{footnote}
The identity of enumerators is not preserved.
\end{footnote}
or

\item
they are of pointer type and they have the same pointer value, or

\item
they are of pointer-to-member type and they refer to the same class member
or are both the null member pointer value, or

\item
they are of reference type and they refer to the same object or function, or

\item
they are of array type and their corresponding elements are template-argument-equivalent,
\begin{footnote}
An array as a \grammarterm{template-parameter} decays to a pointer.
\end{footnote}
or

\item
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, or

\item
they are of a closure type\iref{expr.prim.lambda.closure}, or

\item
they are of class type and
their corresponding direct subobjects and reference members are template-argument-equivalent.
\end{itemize}

\pnum
\begin{example}
\begin{codeblock}
template<class E, int size> class buffer { @\commentellip@ };
buffer<char,2*512> x;
buffer<char,1024> y;
\end{codeblock}
declares
\tcode{x}
and
\tcode{y}
to be of the same type, and
\begin{codeblock}
template<class T, void(*err_fct)()> class list { @\commentellip@ };
list<int,&error_handler1> x1;
list<int,&error_handler2> x2;
list<int,&error_handler2> x3;
list<char,&error_handler2> x4;
\end{codeblock}
declares
\tcode{x2}
and
\tcode{x3}
to be of the same type.
Their type differs from the types of
\tcode{x1}
and
\tcode{x4}.

\begin{codeblock}
template<class T> struct X { };
template<class> struct Y { };
template<class T> using Z = Y<T>;
X<Y<int> > y;
X<Z<int> > z;
\end{codeblock}
declares \tcode{y} and \tcode{z} to be of the same type.
\end{example}

\pnum
If an expression $e$ is type-dependent\iref{temp.dep.expr},
\tcode{decltype($e$)}
denotes a unique dependent type. Two such \grammarterm{decltype-specifier}{s}
refer to the same type only if their \grammarterm{expression}{s} are
equivalent\iref{temp.over.link}.
\begin{note}
However, such a type might be aliased,
e.g., by a \grammarterm{typedef-name}.
\end{note}

\pnum
For a type template parameter pack \tcode{T},
\tcode{T...[}\grammarterm{constant-expression}\tcode{]} denotes
a unique dependent type.

\pnum
If the \grammarterm{constant-expression} of a \grammarterm{pack-index-specifier}
is value-dependent,
two such \grammarterm{pack-index-specifier}s refer to the same type
only if their \grammarterm{constant-expression}s are equivalent\iref{temp.over.link}.
Otherwise, two such \grammarterm{pack-index-specifier}s refer to the same type
only if their indexes have the same value.

\rSec1[temp.decls]{Template declarations}

\rSec2[temp.decls.general]{General}

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

\pnum
A \defnadj{primary}{template} declaration is one
in which the name of the template is not followed by
a \grammarterm{template-argument-list}.
The template argument list of a primary template is
the template argument list of its \grammarterm{template-head}\iref{temp.arg}.
A template declaration in which the name of the template is followed by
a \grammarterm{template-argument-list} is
a partial specialization\iref{temp.spec.partial} of
the template named in the declaration,
which shall be a class or variable template.

\pnum
For purposes of name lookup and instantiation,
default arguments,
\grammarterm{type-constraint}{s},
\grammarterm{requires-clause}{s}\iref{temp.pre},
and
\grammarterm{noexcept-specifier}{s}
of function templates
and
of member functions of class templates
are considered definitions;
each
default argument,
\grammarterm{type-constraint},
\grammarterm{requires-clause},
or
\grammarterm{noexcept-specifier}
is a separate definition
which is unrelated
to the templated function definition or
to any other
default arguments,
\grammarterm{type-constraint}{s},
\grammarterm{requires-clause}{s},
or
\grammarterm{noexcept-specifier}{s}.
For the purpose of instantiation, the substatements of a constexpr if
statement\iref{stmt.if} are considered definitions.
For the purpose of name lookup and instantiation,
the \grammarterm{compound-statement} of an \grammarterm{expansion-statement}
is considered a template definition.

\pnum
Because an \grammarterm{alias-declaration} cannot declare a
\grammarterm{template-id}, it is not possible to partially or
explicitly specialize an alias template.

\rSec2[temp.class]{Class templates}

\rSec3[temp.class.general]{General}

\pnum
A
\defnx{class template}{template!class}
defines the layout and operations
for an unbounded set of related types.

\pnum
\begin{example}
It is possible for a single class template
\tcode{List}
to provide an unbounded set of class definitions:
one class \tcode{List<T>} for every type \tcode{T},
each describing a linked list of elements of type \tcode{T}.
Similarly, a class template \tcode{Array} describing a contiguous,
dynamic array can be defined like this:
\begin{codeblock}
template<class T> class Array {
  T* v;
  int sz;
public:
  explicit Array(int);
  T& operator[](int);
  T& elem(int i) { return v[i]; }
};
\end{codeblock}
The prefix \tcode{\keyword{template}<class T>}
specifies that a template is being declared and that a
\grammarterm{type-name} \tcode{T}
can be used in the declaration.
In other words,
\tcode{Array}
is a parameterized type with
\tcode{T}
as its parameter.
\end{example}

\pnum
\begin{note}
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 the
\grammarterm{template-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 \grammarterm{template-head}\iref{temp.arg}.
\begin{example}
\begin{codeblock}
template<class T1, class T2> struct A {
  void f1();
  void f2();
};

template<class T2, class T1> void A<T2,T1>::f1() { }    // OK
template<class T2, class T1> void A<T1,T2>::f2() { }    // error
\end{codeblock}

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

template<class ... Types> void B<Types ...>::f3() { }   // OK
template<class ... Types> void B<Types>::f4() { }       // error
\end{codeblock}

\begin{codeblock}
template<typename T> concept C = true;
template<typename T> concept D = true;

template<C T> struct S {
  void f();
  void g();
  void h();
  template<D U> struct Inner;
};

template<C A> void S<A>::f() { }        // OK, \grammarterm{template-head}{s} match
template<typename T> void S<T>::g() { } // error: no matching declaration for \tcode{S<T>}

template<typename T> requires C<T>      // ill-formed, no diagnostic required: \grammarterm{template-head}{s} are
void S<T>::h() { }                      // functionally equivalent but not equivalent

template<C X> template<D Y>
struct S<X>::Inner { };                 // OK
\end{codeblock}
\end{example}
\end{note}

\pnum
In a partial specialization,
explicit specialization or
explicit instantiation of a class template,
the \grammarterm{class-key}
shall agree in kind with the original class template declaration\iref{dcl.type.elab}.

\rSec3[temp.mem.func]{Member functions of class templates}

\pnum
\indextext{template!member function}%
A member function
of a class template
may be defined outside of the class
template definition in which it is declared.
\begin{example}
\begin{codeblock}
template<class T> class Array {
  T* v;
  int sz;
public:
  explicit Array(int);
  T& operator[](int);
  T& elem(int i) { return v[i]; }
};
\end{codeblock}

declares three member functions of a class template.
The subscript function can be defined like this:

\begin{codeblock}
template<class T> T& Array<T>::operator[](int i) {
  if (i<0 || sz<=i) error("Array: range error");
  return v[i];
}
\end{codeblock}

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

template<typename T> struct S {
  void f() requires C<T>;
  void g() requires C<T>;
};

template<typename T>
  void S<T>::f() requires C<T> { }      // OK
template<typename T>
  void S<T>::g() { }                    // error: no matching function in \tcode{S<T>}
\end{codeblock}
\end{example}

\pnum
The
\grammarterm{template-argument}{s}
for a member function of a class template are determined by the
\grammarterm{template-argument}{s}
of the type of the object for which the member function is called.
\begin{example}
The
\grammarterm{template-argument}
for
\tcode{Array<T>::operator[]}
will be determined by the
\tcode{Array}
to which the subscripting operation is applied.

\begin{codeblock}
Array<int> v1(20);
Array<dcomplex> v2(30);

v1[3] = 7;                              // \tcode{Array<int>::operator[]}
v2[3] = dcomplex(7,8);                  // \tcode{Array<dcomplex>::operator[]}
\end{codeblock}
\end{example}

\rSec3[temp.deduct.guide]{Deduction guides}
\indextext{deduction!class template argument}%

\pnum
Deduction guides are used
when a \grammarterm{template-name} or \grammarterm{splice-type-specifier}
appears as a type specifier
for a deduced class type\iref{dcl.type.class.deduct}.
Deduction guides are not found by name lookup.
Instead, when performing class template argument deduction\iref{over.match.class.deduct},
all reachable deduction guides declared for the class template are considered.

\begin{bnf}
\nontermdef{deduction-guide}\br
    \opt{explicit-specifier} template-name \terminal{(} parameter-declaration-clause \terminal{)} \terminal{->} simple-template-id \opt{requires-clause} \terminal{;}
\end{bnf}

\pnum
\begin{example}
\begin{codeblock}
template<class T, class D = int>
struct S {
  T data;
};
template<class U>
S(U) -> S<typename U::type>;

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

\pnum
The same restrictions apply
to the \grammarterm{parameter-declaration-clause}
of a deduction guide
as in a function declaration\iref{dcl.fct},
except that a generic parameter type placeholder\iref{dcl.spec.auto}
shall not appear in the \grammarterm{parameter-declaration-clause} of
a deduction guide.
The \grammarterm{simple-template-id}
shall name a class template specialization.
The \grammarterm{template-name}
shall be the same \grammarterm{identifier}
as the \grammarterm{template-name}
of the \grammarterm{simple-template-id}.
A \grammarterm{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 \grammarterm{parameter-declaration-clause}{s}
if either is reachable from the other.

\rSec3[temp.mem.class]{Member classes of class templates}

\pnum
A member class of a class template may be defined outside the class template
definition in which it is declared.
\begin{note}
The member class must be defined before its first use that requires
an instantiation\iref{temp.inst}.
For example,
\begin{codeblock}
template<class T> struct A {
  class B;
};
A<int>::B* b1;                          // OK, requires \tcode{A} to be defined but not \tcode{A::B}
template<class T> class A<T>::B { };
A<int>::B  b2;                          // OK, requires \tcode{A::B} to be defined
\end{codeblock}
\end{note}

\rSec3[temp.static]{Static data members of class templates}

\pnum
\indextext{member!template and \tcode{static}}%
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.
\begin{example}
\begin{codeblock}
template<class T> class X {
  static T s;
};
template<class T> T X<T>::s = 0;

struct limits {
  template<class T>
    static const T min;                 // declaration
};

template<class T>
  const T limits::min = { };            // definition
\end{codeblock}
\end{example}

\pnum
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.
\begin{example}
\begin{codeblock}
template <class T> struct A {
  static int i[];
};
template <class T> int A<T>::i[4];      // 4 elements
template <> int A<int>::i[] = { 1 };    // OK, 1 element
\end{codeblock}
\end{example}

\rSec3[temp.mem.enum]{Enumeration members of class templates}

\pnum
An enumeration member of a class template may be defined outside the class
template definition.
\begin{example}
\begin{codeblock}
template<class T> struct A {
  enum E : T;
};
template<class T> enum A<T>::E : T { e1, e2 };
A<int>::E e = A<int>::e1;
\end{codeblock}
\end{example}

\rSec2[temp.mem]{Member templates}

\pnum
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 \grammarterm{template-head} equivalent to that
of the class template followed by
a \grammarterm{template-head} equivalent to that
of the member template\iref{temp.over.link}.
\begin{example}
\begin{codeblock}
template<class T> struct string {
  template<class T2> int compare(const T2&);
  template<class T2> string(const string<T2>& s) { @\commentellip@ }
};

template<class T> template<class T2> int string<T>::compare(const T2& s) {
}
\end{codeblock}
\end{example}
\begin{example}
\begin{codeblock}
template<typename T> concept C1 = true;
template<typename T> concept C2 = sizeof(T) <= 4;

template<C1 T> struct S {
  template<C2 U> void f(U);
  template<C2 U> void g(U);
};

template<C1 T> template<C2 U>
void S<T>::f(U) { }             // OK
template<C1 T> template<typename U>
void S<T>::g(U) { }             // error: no matching function in \tcode{S<T>}
\end{codeblock}
\end{example}

\pnum
A local class of non-closure type shall not have member templates.
Access control rules\iref{class.access}
apply to member template names.
A destructor shall not be a member
template.
A non-template member function\iref{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.
\begin{example}
\begin{codeblock}
template <class T> struct A {
  void f(int);
  template <class T2> void f(T2);
};

template <> void A<int>::f(int) { }                 // non-template member function
template <> template <> void A<int>::f<>(int) { }   // member function template specialization

int main() {
  A<char> ac;
  ac.f(1);                                          // non-template
  ac.f('c');                                        // template
  ac.f<>(1);                                        // template
}
\end{codeblock}
\end{example}

\pnum
A member function template shall not be declared \keyword{virtual}.
\begin{example}
\begin{codeblock}
template <class T> struct AA {
  template <class C> virtual void g(C);             // error
  virtual void f();                                 // OK
};
\end{codeblock}
\end{example}

\pnum
A specialization of
a member function template does not override a virtual function from a
base class.
\begin{example}
\begin{codeblock}
class B {
  virtual void f(int);
};

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

\pnum
\begin{note}
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\iref{class.conv.fct}.
\begin{example}
\begin{codeblock}
struct A {
  template <class T> operator T*();
};
template <class T> A::operator T*() { return 0; }
template <> A::operator char*() { return 0; }       // specialization
template A::operator void*();                       // explicit instantiation

int main() {
  A a;
  int* ip;
  ip = a.operator int*();       // explicit call to template operator \tcode{A::operator int*()}
}
\end{codeblock}
\end{example}
An expression designating
a particular specialization of a conversion function template
can only be formed with a \grammarterm{splice-expression}.
There is no analogous syntax to form a \grammarterm{template-id}\iref{temp.names}
for such a function
by providing an explicit template argument list\iref{temp.arg.explicit}.
\end{note}

\rSec2[temp.variadic]{Variadic templates}

\pnum
A \defn{template parameter pack} is a template parameter
that accepts zero or more template arguments.
\begin{example}
\begin{codeblock}
template<class ... Types> struct Tuple { };

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

\pnum
A \defn{function parameter pack} is a function parameter
that accepts zero or more function arguments.
\begin{example}
\begin{codeblock}
template<class ... Types> void f(Types ... args);

f();                            // \tcode{args} contains no arguments
f(1);                           // \tcode{args} contains one argument: \tcode{int}
f(2, 1.0);                      // \tcode{args} contains two arguments: \tcode{int} and \tcode{double}
\end{codeblock}
\end{example}

\pnum
An \defnx{\grammarterm{init-capture} pack}{init-capture pack@\fakegrammarterm{init-capture} pack}
is a lambda capture that introduces an \grammarterm{init-capture}
for each of the elements in the pack expansion of its \grammarterm{initializer}.
\begin{example}
\begin{codeblock}
template <typename... Args>
void foo(Args... args) {
    [...xs=args]{
        bar(xs...);             // \tcode{xs} is an \grammarterm{init-capture} pack
    };
}

foo();                          // \tcode{xs} contains zero \grammarterm{init-capture}s
foo(1);                         // \tcode{xs} contains one \grammarterm{init-capture}
\end{codeblock}
\end{example}

\pnum
A \defn{structured binding pack} is an \grammarterm{sb-identifier}
that introduces zero or more structured bindings\iref{dcl.struct.bind}.
\begin{example}
\begin{codeblock}
auto foo() -> int(&)[2];

template <class T>
void g() {
  auto [...a] = foo();          // \tcode{a} is a structured binding pack containing two elements
  auto [b, c, ...d] = foo();    // \tcode{d} is a structured binding pack containing zero elements
}
\end{codeblock}
\end{example}

\pnum
A \defn{pack} is
a template parameter pack,
a function parameter pack,
an \grammarterm{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 \grammarterm{init-capture} pack
is the number of elements in the pack expansion of its \grammarterm{initializer}.

\pnum
\indextext{pattern|see{pack expansion, pattern}}%
A \defn{pack expansion}
consists of a \defnx{pattern}{pack expansion!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:

\begin{itemize}
\item In a function parameter pack\iref{dcl.fct}; the pattern is the
\grammarterm{parameter-declaration} without the ellipsis.

\item In a \grammarterm{using-declaration}\iref{namespace.udecl};
the pattern is a \grammarterm{using-declarator}.

\item In a \grammarterm{friend-type-declaration}\iref{class.mem.general};
the pattern is a \grammarterm{friend-type-specifier}.

\item In a template parameter pack that is a pack expansion\iref{temp.param}:
\begin{itemize}
\item
if the template parameter pack is a \grammarterm{parameter-declaration};
the pattern is the \grammarterm{parameter-declaration} without the ellipsis;

\item
if the template parameter pack is a \grammarterm{type-parameter};
the pattern is the corresponding \grammarterm{type-parameter}
without the ellipsis;

\item
if the template parameter pack is a template template parameter;
the pattern is the corresponding
\grammarterm{type-tt-parameter},
\grammarterm{variable-tt-parameter}, or
\grammarterm{concept-tt-parameter}
without the ellipsis.
\end{itemize}

\item In an \grammarterm{initializer-list}\iref{dcl.init};
the pattern is an \grammarterm{initializer-clause}.

\item In a \grammarterm{base-specifier-list}\iref{class.derived};
the pattern is a \grammarterm{base-specifier}.

\item In a \grammarterm{mem-initializer-list}\iref{class.base.init} for a
\grammarterm{mem-initializer} whose \grammarterm{mem-initializer-id} denotes a
base class; the pattern is the \grammarterm{mem-initializer}.

\item In a \grammarterm{template-argument-list}\iref{temp.arg};
the pattern is a \grammarterm{template-argument}.

\item In an \grammarterm{attribute-list}\iref{dcl.attr.grammar};
the pattern is an \grammarterm{attribute}.

\item
In an \grammarterm{annotation-list}\iref{dcl.attr.grammar};
the pattern is an \grammarterm{annotation}.

\item In an \grammarterm{alignment-specifier}\iref{dcl.align}; the pattern is
the \grammarterm{alignment-specifier} without the ellipsis.

\item In a \grammarterm{capture-list}\iref{expr.prim.lambda.capture}; the pattern is
the \grammarterm{capture} without the ellipsis.

\item In a \tcode{sizeof...} expression\iref{expr.sizeof}; the pattern is an
\grammarterm{identifier}.

\item In a \grammarterm{pack-index-expression};
the pattern is an \grammarterm{identifier}.

\item In a \grammarterm{pack-index-specifier};
the pattern is a \grammarterm{typedef-name}.

\item In a \grammarterm{fold-expression}\iref{expr.prim.fold};
the pattern is the \grammarterm{cast-expression}
that contains an unexpanded pack.

\item In a fold expanded constraint\iref{temp.constr.fold};
the pattern is the constraint of that fold expanded constraint.
\end{itemize}

\begin{example}
\begin{codeblock}
template<class ... Types> void f(Types ... rest);
template<class ... Types> void g(Types ... rest) {
  f(&rest ...);     // ``\tcode{\&rest ...}'' is a pack expansion; ``\tcode{\&rest}'' is its pattern
}
\end{codeblock}
\end{example}

\pnum
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.

\pnum
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 called
\defnx{unexpanded packs}{pack!unexpanded} 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.
\begin{example}
\begin{codeblock}
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;
    // \tcode{T1} is \tcode{Tuple<Pair<short, unsigned short>, Pair<int, unsigned>>}
typedef zip<short>::with<unsigned short, unsigned>::type T2;
    // error: different number of arguments specified for \tcode{Args1} and \tcode{Args2}

template<class ... Args>
  void g(Args ... args) {                   // OK, \tcode{Args} is expanded by the function parameter pack \tcode{args}
    f(const_cast<const Args*>(&args)...);   // OK, ``\tcode{Args}'' and ``\tcode{args}'' are expanded
    f(5 ...);                               // error: pattern does not contain any packs
    f(args);                                // error: pack ``\tcode{args}'' is not expanded
    f(h(args ...) + args ...);              // OK, first ``\tcode{args}'' expanded within \tcode{h},
                                            // second ``\tcode{args}'' expanded within \tcode{f}
  }
\end{codeblock}
\end{example}

\pnum
The instantiation of a pack expansion considers
items $\tcode{E}_1, \tcode{E}_2, \dotsc, \tcode{E}_N$,
where
$N$ is the number of elements in the pack expansion parameters.
Each $\tcode{E}_i$ is generated by instantiating the pattern and
replacing each pack expansion parameter with its $i^\text{th}$ element.
Such an element, in the context of the instantiation, is interpreted as
follows:

\begin{itemize}
\item
if the pack is a template parameter pack, the element is
\begin{itemize}
\item
a \grammarterm{typedef-name} for a type template parameter pack,
\item
an \grammarterm{id-expression} for a constant template parameter pack, or
\item
a \grammarterm{template-name} for a template template parameter pack
\end{itemize}
designating the $i^\text{th}$ corresponding
type, constant, or template template argument;

\item
if the pack is a function parameter pack, the element is an
\grammarterm{id-expression}
designating the $i^\text{th}$ function parameter
that resulted from instantiation of
the function parameter pack declaration;

\item
if the pack is an \grammarterm{init-capture} pack,
the element is an \grammarterm{id-expression}
designating the variable introduced by
the $i^\text{th}$ \grammarterm{init-capture}
that resulted from instantiation of
the \grammarterm{init-capture} pack declaration;
otherwise

\item
if the pack is a structured binding pack,
the element is an \grammarterm{id-expression}
designating the $i^\textrm{th}$ structured binding in the pack
that resulted from the structured binding declaration.
\end{itemize}
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.

\pnum
The instantiation of a \tcode{sizeof...} expression\iref{expr.sizeof} produces
an integral constant with value $N$.

\pnum
When instantiating a \grammarterm{pack-index-expression} $P$,
let $K$ be the index of $P$.
The instantiation of $P$ is the \grammarterm{id-expression} $\tcode{E}_K$.

\pnum
When instantiating a \grammarterm{pack-index-specifier} $P$,
let $K$ be the index of $P$.
The instantiation of $P$ is the \grammarterm{typedef-name} $\tcode{E}_K$.

\pnum
The instantiation of an \grammarterm{alignment-specifier} with an ellipsis
produces $\tcode{E}_1$ $\tcode{E}_2$ $\dotsc$ $\tcode{E}_N$.

\pnum
The instantiation of a \grammarterm{fold-expression}\iref{expr.prim.fold} produces:
\begin{itemize}
\item
% Note: "\space" used below because " " inside tcode adds too much whitespace;
% one could optionally use mathfont inside tcode, e.g., "\tcode{($ $}".
\tcode{(}\space
\tcode{((}$\mathtt{E}_1$
           \placeholder{op} $\mathtt{E}_2$\tcode{)}
           \placeholder{op} $\cdots$\tcode{)}
           \placeholder{op} $\mathtt{E}_N$
\space\tcode{)}
for a unary left fold,
\item
\tcode{(}\space
         $\mathtt{E}_1$     \placeholder{op}
\tcode{(}$\cdots$           \placeholder{op}
\tcode{(}$\mathtt{E}_{N-1}$ \placeholder{op}
         $\mathtt{E}_N$\tcode{))}
\space\tcode{)}
for a unary right fold,
\item
\tcode{(}\space
\tcode{(((}$\mathtt{E}$
            \placeholder{op} $\mathtt{E}_1$\tcode{)}
            \placeholder{op} $\mathtt{E}_2$\tcode{)}
            \placeholder{op} $\cdots$\tcode{)}
            \placeholder{op} $\mathtt{E}_N$
\space\tcode{)}
for a binary left fold, and
\item
\tcode{(}\space
         $\mathtt{E}_1$     \placeholder{op}
\tcode{(}$\cdots$           \placeholder{op}
\tcode{(}$\mathtt{E}_{N-1}$ \placeholder{op}
\tcode{(}$\mathtt{E}_{N}$   \placeholder{op}
         $\mathtt{E}$\tcode{)))}
\space\tcode{)}
for a binary right fold.
\end{itemize}

In each case,
\placeholder{op} is the \grammarterm{fold-operator}.
For a binary fold,
$\mathtt{E}$ is generated
by instantiating the \grammarterm{cast-expression}
that did not contain an unexpanded pack.
\begin{example}
\begin{codeblock}
template<typename ...Args>
  bool all(Args ...args) { return (... && args); }

bool b = all(true, true, true, false);
\end{codeblock}
Within the instantiation of \tcode{all},
the returned expression expands to
\tcode{((true \&\& true) \&\& true) \&\& false},
which evaluates to \tcode{false}.
\end{example}
If $N$ is zero for a unary fold,
the value of the expression is shown in \tref{temp.fold.empty};
if the operator is not listed in \tref{temp.fold.empty},
the instantiation is ill-formed.

\begin{floattable}{Value of folding empty sequences}{temp.fold.empty}
{ll}
\topline
\lhdr{Operator} & \rhdr{Value when pack is empty} \\
\capsep
\tcode{\&\&}    & \tcode{true}   \\
\tcode{||}      & \tcode{false}  \\
\tcode{,}       & \tcode{void()} \\
\end{floattable}

\pnum
A fold expanded constraint is not instantiated\iref{temp.constr.fold}.

\pnum
The instantiation of any other pack expansion
produces a list of elements $\tcode{E}_1, \tcode{E}_2, \dotsc, \tcode{E}_N$.
\begin{note}
The variety of list varies with the context:
\grammarterm{expression-list},
\grammarterm{base-specifier-list},
\grammarterm{template-argument-list}, etc.
\end{note}
When $N$ is zero, the instantiation of the expansion produces an empty list.
\begin{example}
\begin{codeblock}
template<class... T> struct X : T... { };
template<class... T> void f(T... values) {
  X<T...> x(values...);
}

template void f<>();    // OK, \tcode{X<>} has no base classes
                        // \tcode{x} is a variable of type \tcode{X<>} that is value-initialized
\end{codeblock}
\end{example}

\rSec2[temp.friend]{Friends}

\pnum
\indextext{friend!template and}%
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.
\begin{example}
\begin{codeblock}
template<class T> class task;
template<class T> task<T>* preempt(task<T>*);

template<class T> class task {
  friend void next_time();
  friend void process(task<T>*);
  friend task<T>* preempt<T>(task<T>*);
  template<class C> friend int func(C);

  friend class task<int>;
  template<class P> friend class frd;
};
\end{codeblock}

Here,
each specialization of the
\tcode{task}
class template has the function
\tcode{next_time}
as a friend;
because
\tcode{process}
does not have explicit
\grammarterm{template-argument}{s},
each specialization of the
\tcode{task}
class template has an appropriately typed function
\tcode{process}
as a friend, and this friend is not a function template specialization;
because the friend
\tcode{preempt}
has an explicit
\grammarterm{template-argument}
\tcode{T},
each specialization of the
\tcode{task}
class template has the appropriate specialization of the function
template
\tcode{preempt}
as a friend;
and each specialization of the
\tcode{task}
class template has all specializations of the function template
\tcode{func}
as friends.
Similarly,
each specialization of the
\tcode{task}
class template has the class template specialization
\tcode{task<int>}
as a friend, and has all specializations of the class template
\tcode{frd}
as friends.
\end{example}

\pnum
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.
\begin{note}
They can introduce entities
that belong to an enclosing namespace scope\iref{dcl.meaning},
in which case they are attached to
the same module as the class template\iref{module.unit}.
\end{note}

\pnum
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.
\begin{example}
\begin{codeblock}
class A {
  template<class T> friend class B;                 // OK
  template<class T> friend void f(T) { @\commentellip@ }  // OK
};
\end{codeblock}
\end{example}

\pnum
A template friend declaration specifies that all specializations of that
template, whether they are implicitly instantiated\iref{temp.inst}, partially
specialized\iref{temp.spec.partial} or explicitly specialized\iref{temp.expl.spec},
are friends of the class containing the template friend declaration.
\begin{example}
\begin{codeblock}
class X {
  template<class T> friend struct A;
  class Y { };
};

template<class T> struct A { X::Y ab; };            // OK
template<class T> struct A<T*> { X::Y ab; };        // OK
\end{codeblock}
\end{example}

\pnum
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 \grammarterm{elaborated-type-specifier},
in either case with a \grammarterm{nested-name-specifier}
ending with a \grammarterm{simple-template-id}, \placeholder{C},
whose \grammarterm{template-name} names a class template.
The template parameters of the template friend declaration
shall be deducible from \placeholder{C}\iref{temp.deduct.type}.
In this case,
a member of a specialization \placeholder{S} of the class template
is a friend of the class granting friendship
if deduction of the template parameters
of \placeholder{C} from \placeholder{S} succeeds, and
substituting the deduced template arguments into the friend declaration
produces a declaration that corresponds to
the member of the specialization.
\begin{example}
\begin{codeblock}
template<class T> struct A {
  struct B { };
  void f();
  struct D {
    void g();
  };
  T h();
  template<T U> T i();
};
template<> struct A<int> {
  struct B { };
  int f();
  struct D {
    void g();
  };
  template<int U> int i();
};
template<> struct A<float*> {
  int *h();
};

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

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

\pnum
Friend declarations shall not declare partial specializations.
\begin{example}
\begin{codeblock}
template<class T> class A { };
class X {
  template<class T> friend class A<T*>;         // error
};
\end{codeblock}
\end{example}

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

\pnum
A non-template friend declaration
with a \grammarterm{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.

\rSec2[temp.spec.partial]{Partial specialization}

\rSec3[temp.spec.partial.general]{General}

\pnum
\indextext{specialization!class template partial}%
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\iref{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.

\pnum
Two partial specialization declarations declare the same entity
if they are partial specializations of the same template and have equivalent
\grammarterm{template-head}s and template argument lists\iref{temp.over.link}.
Each partial specialization is a distinct template.

\pnum
\begin{example}
\begin{codeblock}
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 T>                   class A<int, T*, 5> { };
template<class T1, class T2, int I> class A<T1, T2*, I> { };
\end{codeblock}

The first declaration declares the primary (unspecialized) class template.
The second and subsequent declarations declare partial specializations of
the primary template.
\end{example}

\pnum
A partial specialization may be constrained\iref{temp.constr}.
\begin{example}
\begin{codeblock}
template<typename T> concept C = true;

template<typename T> struct X { };
template<typename T> struct X<T*> { };          // \#1
template<C T> struct X<T> { };                  // \#2
\end{codeblock}
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\iref{temp.constr.order}.
\end{example}

\pnum
The template argument list of a partial specialization is
the \grammarterm{template-argument-list} following the name of the template.

\pnum
A partial specialization may be declared in any
scope in which the corresponding primary template
may be defined\iref{dcl.meaning,class.mem,temp.mem}.
\begin{example}
\begin{codeblock}
template<class T> struct A {
  struct C {
    template<class T2> struct B { };
    template<class T2> struct B<T2**> { };      // partial specialization \#1
  };
};

// partial specialization of \tcode{A<T>::C::B<T2>}
template<class T> template<class T2>
  struct A<T>::C::B<T2*> { };                   // \#2

A<short>::C::B<int*> absip;                     // uses partial specialization \#2
\end{codeblock}
\end{example}

\pnum
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.
\begin{note}
One consequence is
that a \grammarterm{using-declaration}
which refers to a class template does not restrict the set of partial specializations
that are found through the \grammarterm{using-declaration}.
\end{note}
\begin{example}
\begin{codeblock}
namespace N {
  template<class T1, class T2> class A { };     // primary template
}

using N::A;                                     // refers to the primary template

namespace N {
  template<class T> 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{codeblock}
\end{example}

\pnum
A constant template argument is non-specialized if it is the name of a constant
template parameter.
All other constant template arguments are specialized.

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

\begin{itemize}
\item
The type of a template parameter corresponding to a specialized constant template
argument shall not be dependent on a parameter of the partial specialization.
\begin{example}
\begin{codeblock}
template <class T, T t> struct C {};
template <class T> struct C<T, 1>;              // error

template< int X, int (*array_ptr)[X] > class A {};
int array[5];
template< int X > class A<X,&array> { };        // error
\end{codeblock}

\end{example}
\item
The partial specialization shall be more specialized than the primary
template\iref{temp.spec.partial.order}.

\item
The template parameter list of a partial specialization shall not contain default
template argument values.
\begin{footnote}
There is no context in which they would be used.
\end{footnote}
\item
An argument shall not contain an unexpanded pack. If
an argument is a pack expansion\iref{temp.variadic}, it shall be
the last argument in the template argument list.
\end{itemize}

\pnum
The usual access checking rules do not apply to non-dependent names
used to specify template arguments of the \grammarterm{simple-template-id}
of the partial specialization.
\begin{note}
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}

\rSec3[temp.spec.partial.match]{Matching of partial specializations}

\pnum
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.

\begin{itemize}
\item
If exactly one matching partial specialization is found, the instantiation is
generated from that partial specialization.
\item
If more than one matching partial specialization is found,
the partial order rules\iref{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.
\item
If no matches are found, the instantiation is generated from the
primary template.
\end{itemize}

\pnum
A partial specialization matches a given actual template argument
list if the template arguments of the partial specialization can be
deduced from the actual template argument list\iref{temp.deduct},
and the deduced template arguments satisfy the associated constraints
of the partial specialization, if any\iref{temp.constr.decl}.
\begin{example}
\begin{codeblock}
template<class T1, class T2, int I> class A             { };    // \#1
template<class T, int I>            class A<T, T*, I>   { };    // \#2
template<class T1, class T2, int I> class A<T1*, T2, I> { };    // \#3
template<class T>                   class A<int, T*, 5> { };    // \#4
template<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, \tcode{T} is \tcode{int}, \tcode{I} is \tcode{1}
A<int, char*, 5> a3;                    // uses \#4, \tcode{T} is \tcode{char}
A<int, char*, 1> a4;                    // uses \#5, \tcode{T1} is \tcode{int}, \tcode{T2} is \tcode{char}, \tcode{I} is \tcode{1}
A<int*, int*, 2> a5;                    // ambiguous: matches \#3 and \#5
\end{codeblock}
\end{example}
\begin{example}
\begin{codeblock}
template<typename T> concept C = requires (T t) { t.f(); };

template<typename T> struct S { };      // \#1
template<C T> struct S<T> { };          // \#2

struct Arg { void f(); };

S<int> s1;                              // uses \#1; the constraints of \#2 are not satisfied
S<Arg> s2;                              // uses \#2; both constraints are satisfied but \#2 is more specialized
\end{codeblock}
\end{example}

\pnum
If the template arguments of a partial specialization cannot be deduced
because of the structure of its \grammarterm{template-parameter-list}
and the \grammarterm{template-id},
the program is ill-formed.
\begin{example}
\begin{codeblock}
template <int I, int J> struct A {};
template <int I> struct A<I+5, I*2> {};     // error

template <int I> struct A<I, I> {};         // OK

template <int I, int J, int K> struct B {};
template <int I> struct B<I, I*2, 2> {};    // OK
\end{codeblock}
\end{example}

\pnum
In a name that refers to a specialization of a class or variable template
(e.g., \tcode{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.

\rSec3[temp.spec.partial.order]{Partial ordering of partial specializations}

\pnum
\indextext{more specialized!class template}%
For two partial specializations,
the first is \defn{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\iref{temp.func.order}:

\begin{itemize}
\item
Each of the two
function templates has the same template parameters
and associated constraints\iref{temp.constr.decl}
as the corresponding partial specialization.
\item
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 \grammarterm{template-argument-list}
of the \grammarterm{simple-template-id}
of the partial specialization.
\end{itemize}

\pnum
\begin{example}
\begin{codeblock}
template<int I, int J, class T> class X { };
template<int I, int J>          class X<I, J, int> { };         // \#1
template<int I>                 class X<I, I, int> { };         // \#2

template<int I0, int J0> void f(X<I0, J0, int>);                // A
template<int I0>         void f(X<I0, I0, int>);                // B

template <auto v>    class Y { };
template <auto* p>   class Y<p> { };                            // \#3
template <auto** pp> class Y<pp> { };                           // \#4

template <auto* p0>   void g(Y<p0>);                            // C
template <auto** pp0> void g(Y<pp0>);                           // D
\end{codeblock}

According to the ordering rules for function templates,
the function template
\placeholder{B}
is more specialized than the function template
\placeholder{A}
and
the function template
\placeholder{D}
is more specialized than the function template
\placeholder{C}.
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}
\begin{example}
\begin{codeblock}
template<typename T> concept C = requires (T t) { t.f(); };
template<typename T> concept D = C<T> && requires (T t) { t.f(); };

template<typename T> class S { };
template<C T> class S<T> { };   // \#1
template<D T> class S<T> { };   // \#2

template<C T> void f(S<T>);     // A
template<D T> void f(S<T>);     // B
\end{codeblock}
The partial specialization \#2 is more specialized than \#1
because \tcode{B} is more specialized than \tcode{A}.
\end{example}

\rSec3[temp.spec.partial.member]{Members of class template partial specializations}

\pnum
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.
\begin{example}
\begin{codeblock}
// primary class template
template<class T, int I> struct A {
  void f();
};

// member of primary class template
template<class T, int I> void A<T,I>::f() { }

// class template partial specialization
template<class T> struct A<T,2> {
  void f();
  void g();
  void h();
};

// member of class template partial specialization
template<class T> void A<T,2>::g() { }

// explicit specialization
template<> 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 \tcode{f} for \tcode{A<T,2>}; the primary template is not used here
}
\end{codeblock}
\end{example}

\pnum
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\iref{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.
\begin{example}
\begin{codeblock}
template<class T> struct A {
  template<class T2> struct B {};                               // \#1
  template<class T2> struct B<T2*> {};                          // \#2
};

template<> template<class T2> struct A<short>::B {};            // \#3

A<char>::B<int*>  abcip;                                        // uses \#2
A<short>::B<int*> absip;                                        // uses \#3
A<char>::B<int>  abci;                                          // uses \#1
\end{codeblock}
\end{example}

\rSec2[temp.fct]{Function templates}

\rSec3[temp.fct.general]{General}

\pnum
A function template defines an unbounded set of related functions.
\begin{example}
A family of sort functions can be declared like this:

\begin{codeblock}
template<class T> class Array { };
template<class T> void sort(Array<T>&);
\end{codeblock}
\end{example}

\pnum
\begin{note}
A function template can have the same name as other function templates
and non-template functions\iref{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.
\begin{footnote}
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\iref{term.odr.use} in a program, it must be defined;
it will not be implicitly instantiated using the function template definition.
\end{footnote}

\rSec3[temp.over.link]{Function template overloading}

\pnum
\indextext{overloading}%
It is possible to overload function templates so that two different
function template specializations have the same type.
\begin{example}

\begin{minipage}{.45\hsize}
\begin{codeblock}
// translation unit 1:
template<class T>
  void f(T*);
void g(int* p) {
  f(p); // calls \tcode{f<int>(int*)}
}
\end{codeblock}
\end{minipage}
\begin{minipage}{.45\hsize}
\begin{codeblock}
// translation unit 2:
template<class T>
  void f(T);
void h(int* p) {
  f(p); // calls \tcode{f<int*>(int*)}
}
\end{codeblock}
\end{minipage}

\end{example}

\pnum
Such specializations are distinct functions and do not violate the one-definition
rule\iref{basic.def.odr}.

\pnum
The signature of a function template
is defined in \ref{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.
\begin{note}
Two distinct function templates can have identical function return types and
function parameter lists, even if overload resolution alone cannot distinguish
them.

\begin{codeblock}
template<class T> void f();
template<int I> void f();       // OK, overloads the first template
                                // distinguishable with an explicit template argument list
\end{codeblock}
\end{note}

\pnum
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.
\begin{example}
\begin{codeblock}
template <int I, int J> A<I+J> f(A<I>, A<J>);   // \#1
template <int K, int L> A<K+L> f(A<K>, A<L>);   // same as \#1
template <int I, int J> A<I-J> f(A<I>, A<J>);   // different from \#1
\end{codeblock}
\end{example}
\begin{note}
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 the
\tcode{sizeof} operator.
\end{note}

\pnum
\indextext{expression!equivalent|see{equivalent, expressions}}%
Two expressions involving template parameters are considered
\defnx{equivalent}{equivalent!expressions}
if two function definitions containing the expressions would satisfy
the one-definition rule\iref{basic.def.odr}, 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\iref{temp.names} may differ
as long as the two \grammarterm{template-id}{s} are the same\iref{temp.type}.
\begin{note}
For instance, \tcode{A<42>} and \tcode{A<40+2>} name the same type.
\end{note}
Two \grammarterm{lambda-expression}{s} are never considered equivalent.
\begin{note}
The intent is to avoid \grammarterm{lambda-expression}{s} appearing in the
signature of a function template with external linkage.
\end{note}
For determining whether two dependent names\iref{temp.dep} are equivalent,
only the name itself is considered, not the result of name lookup.
\begin{note}
If such a dependent name is unqualified,
it is looked up from
a first declaration of the function template\iref{temp.res.general}.
\end{note}
\begin{example}
\begin{codeblock}
template <int I, int J> void f(A<I+J>);         // \#1
template <int K, int L> void f(A<K+L>);         // same as \#1

template <class T> decltype(g(T())) h();
int g(int);
template <class T> decltype(g(T())) h()         // redeclaration of \tcode{h()} uses the earlier lookup\ldots
  { return g(T()); }                            // \ldots{} although the lookup here does find \tcode{g(int)}
int i = h<int>();                               // template argument substitution fails; \tcode{g(int)}
                                                // not considered at the first declaration of \tcode{h()}

// ill-formed, no diagnostic required: the two expressions are functionally equivalent but not equivalent
template <int N> void foo(const char (*s)[([]{}, N)]);
template <int N> void foo(const char (*s)[([]{}, N)]);

// two different declarations because the non-dependent portions are not considered equivalent
template <class T> void spam(decltype([]{}) (*s)[sizeof(T)]);
template <class T> void spam(decltype([]{}) (*s)[sizeof(T)]);
\end{codeblock}
\end{example}
\indextext{expression!functionally equivalent|see{functionally equivalent, expressions}}%
Two potentially evaluated expressions involving template parameters that are not equivalent are
\defnx{functionally equivalent}{functionally equivalent!expressions}
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.
\begin{note}
For instance, one could have redundant parentheses.
\end{note}
\begin{example}
\begin{codeblock}
template<int I> concept C = true;
template<typename T> struct A {
  void f() requires C<42>;      // \#1
  void f() requires true;       // OK, different functions
};
\end{codeblock}
\end{example}

\pnum
Two \grammarterm{template-head}{s} are
\defnx{equivalent}{equivalent!\idxgram{template-head}{s}} if
their \grammarterm{template-parameter-list}{s} have the same length,
corresponding \grammarterm{template-parameter}{s} are equivalent
and are both declared with \grammarterm{type-constraint}s that are equivalent
if either \grammarterm{template-parameter}
is declared with a \grammarterm{type-constraint},
and if either \grammarterm{template-head} has a \grammarterm{requires-clause},
they both have
\grammarterm{requires-clause}{s} and the corresponding
\grammarterm{constraint-expression}{s} are equivalent.
Two \grammarterm{template-parameter}{s} are
\defnx{equivalent}{equivalent!\idxgram{template-parameter}{s}}
under the following conditions:
\begin{itemize}
\item they declare template parameters of the same kind,
\item if either declares a template parameter pack, they both do,
\item if they declare constant template parameters,
they have equivalent types
ignoring the use of \grammarterm{type-constraint}{s} for placeholder types, and
\item if they declare template template parameters,
their \grammarterm{template-head}{s} are equivalent.
\end{itemize}
When determining whether types or \grammarterm{type-constraint}{s}
are equivalent, the rules above are used to compare expressions
involving template parameters.
Two \grammarterm{template-head}{s} are
\defnx{functionally equivalent}{functionally equivalent!\idxgram{template-head}{s}}
if they accept and are satisfied by\iref{temp.constr.constr}
the same set of template argument lists.

\pnum
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
\begin{itemize}
\item
introduce the same name,
\item
have corresponding signatures\iref{basic.scope.scope},
\item
would declare the same entity,
when considering $A$ and $B$ to correspond in that determination\iref{basic.link}, and
\item
accept and are satisfied by the same set of template argument lists,
\end{itemize}
but do not correspond,
the program is ill-formed, no diagnostic required.

\pnum
\begin{note}
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:

\begin{codeblock}
// guaranteed to be the same
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+10>);

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

// ill-formed, no diagnostic required
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+1+2+3+4>);
\end{codeblock}
\end{note}

\rSec3[temp.func.order]{Partial ordering of function templates}

\pnum
\indextext{overloading!resolution!template}%
\indextext{ordering!function template partial|see{template, function, partial ordering}}%
If multiple function templates share a name,
the use of that name can be ambiguous because
template argument deduction\iref{temp.deduct} may identify
a specialization for more than one function template.
\defnx{Partial ordering}{template!function!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:
\begin{itemize}
\item
during overload resolution for a call to a function template specialization\iref{over.match.best};
\item
when the address of a function template specialization is taken;
\item
when a placement operator delete that is a
function template
specialization
is selected to match a placement operator new\iref{basic.stc.dynamic.deallocation,expr.new};
\item
when a friend function declaration\iref{temp.friend}, an
explicit instantiation\iref{temp.explicit} or an explicit specialization\iref{temp.expl.spec} refers to
a function template specialization.
\end{itemize}

\pnum
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.

\pnum
To produce the transformed template, for each
%FIXME: Don't we want to append "template parameter" to each of these?
%FIXME: As is, it reads as if it only applies to "conecpt".
%FIXME: E.g., we mean "type template parameter", not "type".
type, constant,
type template, variable template, or concept
template parameter (including template parameter packs\iref{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.
The type replacing a placeholder
in the type of the value synthesized for a constant template parameter
is a unique synthesized type.

\pnum
%FIXME: What's a "synthesized template"? Do we mean the synthesized
%FIXME: template described above? If so, say so.
A synthesized template has the same \grammarterm{template-head} as
its corresponding template template parameter.

\pnum
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\iref{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$:

\begin{itemize}
\item
The type $X(M)$ is ``rvalue reference to \cv{}~$A$''
if the optional \grammarterm{ref-qualifier} of
$M$ is \tcode{\&\&} or
if $M$ has no \grammarterm{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.

\item
Otherwise, $X(M)$ is ``lvalue reference to \cv{}~$A$''.
\end{itemize}

\begin{note}
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}
\begin{example}
\begin{codeblock}
struct A { };
template<class T> struct B {
  template<class R> int operator*(R&);              // \#1
};

template<class T, class R> int operator*(T&, R&);   // \#2

// The declaration of \tcode{B::operator*} is transformed into the equivalent of
// \tcode{template<class R> int operator*(B<A>\&, R\&);}\quad\quad\quad// \#1a

int main() {
  A a;
  B<A> b;
  b * a;                                            // calls \#1
}
\end{codeblock}
\end{example}

\pnum
Using the transformed function template's function type,
perform type deduction against the other template as described in~\ref{temp.deduct.partial}.

\begin{example}
\begin{codeblock}
template<class T> struct A { A(); };

template<class T> void f(T);
template<class T> void f(T*);
template<class T> void f(const T*);

template<class T> void g(T);
template<class T> void g(T&);

template<class T> void h(const T&);
template<class T> void h(A<T>&);

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

\pnum
\begin{note}
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).
\begin{example}
\begin{codeblock}
template<class T> void f(T);                            // \#1
template<class T> void f(T*, int=1);                    // \#2
template<class T> void g(T);                            // \#3
template<class T> void g(T*, ...);                      // \#4

\end{codeblock}
\begin{codeblock}
int main() {
  int* ip;
  f(ip);                                                // calls \#2
  g(ip);                                                // calls \#4
}
\end{codeblock}
\end{example}
\begin{example}
\begin{codeblock}
template<class T, class U> struct A { };

template<class T, class U> void f(U, A<U, T>* p = 0);   // \#1
template<         class U> void f(U, A<U, U>* p = 0);   // \#2
template<class T         > void g(T, T = T());          // \#3
template<class T, class... U> void g(T, U ...);         // \#4

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

void h(int i) {
  f(&i);                                                // OK, calls \#2
  g(&i);                                                // OK, calls \#3
}
\end{codeblock}
\end{example}
\end{note}

\pnum
If deduction against the other template succeeds for both transformed templates,
constraints can be considered as follows:
\begin{itemize}
\item
If their \grammarterm{template-parameter-list}{s}
(possibly including \grammarterm{template-parameter}{s}
invented for an abbreviated function template\iref{dcl.fct}) or
function parameter lists differ in length,
neither template is more specialized than the other.
\item
Otherwise:
\begin{itemize}
\item
If exactly one of the templates was considered by overload resolution
via a rewritten candidate with reversed order of parameters:
\begin{itemize}
\item
If, for either template, some of the template parameters
are not deducible from their function parameters,
neither template is more specialized than the other.
\item
If there is either no reordering or more than one reordering
of the associated \grammarterm{template-parameter-list}
such that
\begin{itemize}
\item
the corresponding \grammarterm{template-parameter}{s}
of the \grammarterm{template-parameter-list}{s} are equivalent and
\item
the function parameters that positionally correspond
between the two templates are of the same type,
\end{itemize}
neither template is more specialized than the other.
\end{itemize}
\item
Otherwise, if the corresponding \grammarterm{template-parameter}{s}
of the \grammarterm{template-parameter-list}{s}
are not equivalent\iref{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.
\end{itemize}
\item
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.
\item
Otherwise,
if one template is more constrained than the other\iref{temp.constr.order},
the more constrained template is more specialized than the other.
\item
Otherwise, neither template is more specialized than the other.
\end{itemize}
\begin{example}
\begin{codeblock}
template <typename> constexpr bool True = true;
template <typename T> concept C = True<T>;

void f(C auto &, auto &) = delete;
template <C Q> 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 [\tcode{T}, \tcode{U}, \tcode{V}] and [\tcode{U}, \tcode{V}, \tcode{T}]
}
\end{codeblock}
\end{example}

\rSec2[temp.alias]{Alias templates}

\pnum
A \grammarterm{template-declaration} in which the \grammarterm{declaration} is an
\grammarterm{alias-declaration}\iref{dcl.pre} declares the
\grammarterm{identifier} to be an \defnadj{alias}{template}.
An alias template is a name for a family of
types. The name of the alias template is a \grammarterm{template-name}.

\pnum
A
\begin{itemize}
\item
\grammarterm{template-id}
that is not the operand of a \grammarterm{reflect-expression} or
\item
\grammarterm{splice-specialization-specifier}
\end{itemize}
that designates the specialization of
an alias template is equivalent to the associated type obtained by
substitution of its \grammarterm{template-argument}{s} for the
\grammarterm{template-parameter}{s} in the \grammarterm{defining-type-id} of
the alias template.
Any other \grammarterm{template-id}
that names a specialization of an alias template is
a \grammarterm{typedef-name} for a type alias;
such a \grammarterm{template-id} is ill-formed if
forming the associated type results in substitution failure.
\begin{note}
The alias template name is not deduced from such a type\iref{temp.deduct.type}.
\end{note}
\begin{example}
\begin{codeblock}
template<class T> struct Alloc { @\commentellip@ };
template<class T> using Vec = vector<T, Alloc<T>>;
Vec<int> v;         // same as \tcode{vector<int, Alloc<int>> v;}

template<class T>
  void process(Vec<T>& v)
  { @\commentellip@ }

template<class T>
  void process(vector<T, Alloc<T>>& w)
  { @\commentellip@ }     // error: redefinition

template<template<class> class TT>
  void f(TT<int>);

f(v);               // error: \tcode{Vec} not deduced

template<template<class,class> class TT>
  void g(TT<int, Alloc<int>>);
g(v);               // OK, \tcode{TT} = \tcode{vector}
\end{codeblock}

\end{example}

\pnum
However, if the \grammarterm{template-id} is dependent, subsequent template
argument substitution still applies to the \grammarterm{template-id}.
\begin{example}
\begin{codeblock}
template<typename...> using void_t = void;
template<typename T> void_t<typename T::foo> f();
f<int>();           // error: \tcode{int} does not have a nested type \tcode{foo}
\end{codeblock}
\end{example}

\pnum
The \grammarterm{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.
\begin{example}
\begin{codeblock}
template <class T> struct A;
template <class T> using B = typename A<T>::U;
template <class T> struct A {
  typedef B<T> U;
};
B<short> b;         // error: instantiation of \tcode{B<short>} uses own type via \tcode{A<short>::U}
\end{codeblock}
\end{example}

\pnum
The type of a \grammarterm{lambda-expression}
appearing in an alias template declaration
is different between instantiations of that template,
even when the \grammarterm{lambda-expression} is not dependent.
\begin{example}
\begin{codeblock}
template <class T>
  using A = decltype([] { });   // \tcode{A<int>} and \tcode{A<char>} refer to different closure types
\end{codeblock}
\end{example}

\rSec2[temp.concept]{Concept definitions}

\pnum
A \defn{concept} is a template
that defines constraints on its template arguments.

\begin{bnf}
\nontermdef{concept-definition}\br
  \keyword{concept} concept-name \opt{attribute-specifier-seq} \terminal{=} constraint-expression \terminal{;}
\end{bnf}

\begin{bnf}
\nontermdef{concept-name}\br
  identifier
\end{bnf}

\pnum
A \grammarterm{concept-definition}
declares a concept.
Its \grammarterm{identifier} becomes a \grammarterm{concept-name}
referring to that concept
within its scope.
The optional \grammarterm{attribute-specifier-seq} appertains to the concept.
\begin{example}
\begin{codeblock}
template<typename T>
concept C = requires(T x) {
  { x == x } -> std::@\libconcept{convertible_to}@<bool>;
};

template<typename T>
  requires C<T>     // \tcode{C} constrains \tcode{f1(T)} in \grammarterm{constraint-expression}
T f1(T x) { return x; }

template<C T>       // \tcode{C}, as a \grammarterm{type-constraint}, constrains \tcode{f2(T)}
T f2(T x) { return x; }
\end{codeblock}
\end{example}

\pnum
A \grammarterm{concept-definition}
shall inhabit a namespace scope\iref{basic.scope.namespace}.

\pnum
A concept shall not have associated constraints\iref{temp.constr.decl}.

\pnum
A concept is not instantiated\iref{temp.spec}.
\begin{note}
A concept-id\iref{temp.names} is evaluated as an expression.
A concept cannot be
explicitly instantiated\iref{temp.explicit},
explicitly specialized\iref{temp.expl.spec},
or partially specialized\iref{temp.spec.partial}.
\end{note}

\pnum
The \grammarterm{constraint-expression} of a \grammarterm{concept-definition}
is an unevaluated operand\iref{expr.context}.

\pnum
The first declared template parameter of a concept definition is its
\defnx{prototype parameter}{prototype parameter!concept}.
\indextext{type concept|see{concept, type}}%
A \defnx{type concept}{concept!type}
is a concept whose prototype parameter
is a type template parameter.

\rSec1[temp.res]{Name resolution}

\rSec2[temp.res.general]{General}

\pnum
A name that appears in a declaration $D$ of a template $T$ is looked up
from where it appears
in an unspecified declaration of $T$
that either is $D$ itself or is reachable from $D$ and
from which no other declaration of $T$
that contains the usage of the name is reachable.
If the name is dependent (as specified in \ref{temp.dep}),
it is looked up for each specialization (after substitution)
because the lookup depends on a template parameter.
\begin{note}
Some dependent names are also looked up during parsing to determine
that they are dependent or to interpret following \tcode{<} tokens.
Uses of other names might be type-dependent or
value-dependent\iref{temp.dep.expr,temp.dep.constexpr}.
A \grammarterm{using-declarator} is never dependent in a specialization and
is therefore replaced during lookup for that specialization\iref{basic.lookup}.
\end{note}
\begin{example}
\begin{codeblock}
struct A { operator int(); };
template<class B, class T>
struct D : B {
  T get() { return operator T(); }      // \grammarterm{conversion-function-id} is dependent
};
int f(D<A, int> d) { return d.get(); }  // OK, lookup finds \tcode{A::operator int}
\end{codeblock}
\end{example}
\begin{example}
\begin{codeblock}
void f(char);

template<class T> void g(T t) {
  f(1);             // \tcode{f(char)}
  f(T(1));          // dependent
  f(t);             // dependent
  dd++;             // not dependent; error: declaration for \tcode{dd} not found
}

enum E { e };
void f(E);

double dd;
void h() {
  g(e);             // will cause one call of \tcode{f(char)} followed by two calls of \tcode{f(E)}
  g('a');           // will cause three calls of \tcode{f(char)}
}
\end{codeblock}
\end{example}
\begin{example}
\begin{codeblock}
struct A {
  struct B { @\commentellip@ };
  int a;
  int Y;
};

int a;

template<class T> struct Y : T {
  struct B { @\commentellip@ };
  B b;                          // The \tcode{B} defined in \tcode{Y}
  void f(int i) { a = i; }      // \tcode{::a}
  Y* p;                         // \tcode{Y<T>}
};

Y<A> ya;
\end{codeblock}

The members \tcode{A::B}, \tcode{A::a}, and \tcode{A::Y}
of the template argument \tcode{A}
do not affect the binding of names in \tcode{Y<A>}.
\end{example}

\pnum
If the validity or meaning of the program would be changed by
considering a default argument or default template argument
introduced in a declaration that is reachable from
the point of instantiation of a specialization\iref{temp.point}
but is not found by lookup for the specialization,
the program is ill-formed, no diagnostic required.

\begin{bnf}
\nontermdef{typename-specifier}\br
  \keyword{typename} nested-name-specifier identifier\br
  \keyword{typename} nested-name-specifier \opt{\keyword{template}} simple-template-id
\end{bnf}

\pnum
\indextext{component name}%
The component names of a \grammarterm{typename-specifier} are
its \grammarterm{identifier} (if any) and
those of its \grammarterm{nested-name-specifier} and
\grammarterm{simple-template-id} (if any).
A \grammarterm{typename-specifier}
denotes the type or class template
denoted by the \grammarterm{simple-type-specifier}\iref{dcl.type.simple}
formed by omitting the keyword \keyword{typename}.
\begin{note}
The usual qualified name lookup\iref{basic.lookup.qual} applies
even in the presence of \keyword{typename}.
\end{note}
\begin{example}
\begin{codeblock}
struct A {
  struct X { };
  int X;
};
struct B {
  struct X { };
};
template<class T> void f(T t) {
  typename T::X x;
}
void foo() {
  A a;
  B b;
  f(b);             // OK, \tcode{T::X} refers to \tcode{B::X}
  f(a);             // error: \tcode{T::X} refers to the data member \tcode{A::X} not the struct \tcode{A::X}
}
\end{codeblock}
\end{example}

\pnum
\indextext{type-only!context|see{context, type-only}}%
A \defnx{type-only context}{context!type-only} is defined as follows:
A qualified or unqualified name is said to be in
a type-only context if it is the terminal name of
\begin{itemize}
\item a
\grammarterm{typename-specifier},
\grammarterm{type-requirement},
\grammarterm{nested-name-specifier},
\grammarterm{elaborated-type-specifier},
\grammarterm{class-or-decltype},
\grammarterm{using-enum-declarator},
or
\item
a \grammarterm{simple-type-specifier} of a \grammarterm{friend-type-specifier}, or
\item
a \grammarterm{type-specifier} of a
\begin{itemize}
  \item \grammarterm{new-type-id},
  \item \grammarterm{defining-type-id},
  \item \grammarterm{conversion-type-id},
  \item \grammarterm{trailing-return-type},
  \item default argument of a \grammarterm{type-parameter}, or
  \item \grammarterm{type-id} of a
\keyword{static_cast},
\keyword{const_cast},
\keyword{reinterpret_cast}, or
\keyword{dynamic_cast}, or
\end{itemize}
\item a \grammarterm{decl-specifier} of the \grammarterm{decl-specifier-seq} of a
\begin{itemize}
\item \grammarterm{simple-declaration} or \grammarterm{function-definition} in namespace scope,
\item \grammarterm{member-declaration},
\item \grammarterm{parameter-declaration} in a \grammarterm{member-declaration},
\begin{footnote}
This includes friend function declarations.
\end{footnote}
unless that \grammarterm{parameter-declaration} appears in a default argument,
\item \grammarterm{parameter-declaration} in a \grammarterm{declarator}
of a function or function template declaration
whose \grammarterm{declarator-id} is qualified,
unless that \grammarterm{parameter-declaration}
appears in a default argument,
\item \grammarterm{parameter-declaration} in a \grammarterm{lambda-declarator}
or \grammarterm{requirement-parameter-list},
unless that \grammarterm{parameter-declaration} appears in a default argument, or
\item \grammarterm{parameter-declaration} of a \grammarterm{template-parameter}
(which necessarily declares a constant template parameter).
\end{itemize}
\end{itemize}
A \grammarterm{splice-specifier} or
\grammarterm{splice-specialization-specifier}\iref{basic.splice}
is said to be in a type-only context
if a hypothetical qualified name appearing in the same position
would be in a type-only context.
\begin{example}
\begin{codeblock}
template<class T> T::R f();             // OK, return type of a function declaration at global scope
template<class T> void f(T::R);         // ill-formed, no diagnostic required: attempt to declare
                                        // a \keyword{void} variable template
enum class Enum { A, B, C };
template<class T> struct S {
  using Ptr = PtrTraits<T>::Ptr;        // OK, in a \grammarterm{defining-type-id}
  using Alias = [:^^int:];              // OK, in a \grammarterm{defining-type-id}
  T::R f(T::P p) {                      // OK, class scope
    return static_cast<T::R>(p);        // OK, \grammarterm{type-id} of a \keyword{static_cast}
  }
  auto g() -> S<T*>::Ptr;               // OK, \grammarterm{trailing-return-type}
  auto h() -> [:^^S:]<T*>;              // OK, \grammarterm{trailing-return-type}
  using enum [:^^Enum:];                // OK, \grammarterm{using-enum-declarator}
};
template<typename T> void f() {
  void (*pf)(T::X);                     // variable \tcode{pf} of type \tcode{\keyword{void}*} initialized with \tcode{T::X}
  void g(T::X);                         // error: \tcode{T::X} at block scope does not denote a type
                                        // (attempt to declare a \keyword{void} variable)
}
\end{codeblock}
\end{example}

\pnum
A \grammarterm{qualified-id}
whose terminal name is dependent and that is in a type-only context
is considered to denote a type.
A name
that refers to a \grammarterm{using-declarator} whose terminal name is dependent
is interpreted as a \grammarterm{typedef-name}
if the \grammarterm{using-declarator} uses the keyword \keyword{typename}.
\begin{example}
\begin{codeblock}
template <class T> void f(int i) {
  T::x * i;         // expression, not the declaration of a variable \tcode{i}
}

struct Foo {
  typedef int x;
};

struct Bar {
  static int const x = 5;
};

int main() {
  f<Bar>(1);        // OK
  f<Foo>(1);        // error: \tcode{Foo::x} is a type
}
\end{codeblock}
\end{example}

\pnum
\indextext{checking!syntax}%
\indextext{checking!point of error}%
The validity of a templated entity may be checked prior to any instantiation.
\begin{note}
Knowing which names are type names allows the syntax of every template
to be checked in this way.
\end{note}
The program is ill-formed, no diagnostic required, if
\begin{itemize}
\item
no valid specialization,
ignoring \grammarterm{static_assert-declaration}{s} that fail\iref{dcl.pre},
can be generated for a templated entity
or a substatement of a constexpr if statement\iref{stmt.if}
within a templated entity
and the innermost enclosing template is not instantiated, or
\item
no valid specialization,
ignoring \grammarterm{static_assert-declaration}s that fail,
can be generated for the \grammarterm{compound-statement}
of an \grammarterm{expansion-statement} and there is no instantiation of it, or
\item
no valid specialization,
ignoring \grammarterm{static_assert-declaration}{s} that fail,
can be generated for a default \grammarterm{template-argument} and
the default \grammarterm{template-argument} is not used in any instantiation, or
\item
no specialization of an alias template\iref{temp.alias} is valid and
no specialization of the alias template is named in the program, or
\item
any \grammarterm{constraint-expression} in the program, introduced or otherwise,
has (in its normal form) an atomic constraint $A$ where
no satisfaction check of $A$ could be well-formed and
no satisfaction check of $A$ is performed, or
\item
every valid specialization of a variadic template requires an empty template
parameter pack, or
\item
a hypothetical instantiation of a templated entity
immediately following its definition
would be ill-formed
due to a construct
(other than a \grammarterm{static_assert-declaration} that fails)
that does not depend on a template parameter, or
\item
the interpretation of such a construct
in the hypothetical instantiation
is different from
the interpretation of the corresponding construct
in any actual instantiation of the templated entity.
\end{itemize}
\begin{note}
This can happen in situations including the following:
\begin{itemize}
\item a type used in a non-dependent name is incomplete at the point at which a
template is defined but is complete at the point at which an instantiation is
performed, or

\item lookup for a name in the template definition found a \grammarterm{using-declaration},
but the lookup in the corresponding scope in the instantiation
does not find any declarations because the \grammarterm{using-declaration}
was a pack expansion and the corresponding pack is empty, or

\item an instantiation uses a default argument or default template argument
that had not been defined at the point at which the template was defined, or

\item constant expression evaluation\iref{expr.const.core} within the template
instantiation uses
  \begin{itemize}
  \item the value of a const object of integral or unscoped enumeration type or
  \item the value of a \keyword{constexpr} object or
  \item the value of a reference or
  \item the definition of a constexpr function,
  \end{itemize}
and that entity was not defined when the template was defined, or

\item a class template specialization or variable template specialization that
is specified by a non-dependent \grammarterm{simple-template-id} is used by
the template, and either it is instantiated from a partial specialization that
was not defined when the template was defined or it names an explicit
specialization that was not declared when the template was defined.
\end{itemize}
\end{note}

\begin{note}
If a template is instantiated, errors will be diagnosed according
to the other rules in this document.
Exactly when these errors are diagnosed is a quality of implementation issue.
\end{note}
\begin{example}
\begin{codeblock}
int j;
template<class T> class X {
  void f(T t, int i, char* p) {
    t = i;          // diagnosed if \tcode{X::f} is instantiated, and the assignment to \tcode{t} is an error
    p = i;          // may be diagnosed even if \tcode{X::f} is not instantiated
    p = j;          // may be diagnosed even if \tcode{X::f} is not instantiated
    X<T>::g(t);     // OK
    X<T>::h();      // may be diagnosed even if \tcode{X::f} is not instantiated
  }
  void g(T t) {
    +;              // may be diagnosed even if \tcode{X::g} is not instantiated
  }
};

template<class... T> struct A {
  void operator++(int, T... t);                     // error: too many parameters
};
template<class... T> union X : T... { };            // error: union with base class
template<class... T> struct A : T...,  T... { };    // error: duplicate base class
\end{codeblock}
\end{example}

\pnum
\begin{note}
For purposes of name lookup, default arguments and
\grammarterm{noexcept-specifier}{s} of function templates and default
arguments and \grammarterm{noexcept-specifier}{s} of
member functions of class templates are considered definitions\iref{temp.decls}.
\end{note}

\rSec2[temp.local]{Locally declared names}

\pnum
Like normal (non-template) classes, class templates have an
injected-class-name\iref{class.pre}.
The
injected-class-name can be used
as a \grammarterm{template-name} or a \grammarterm{type-name}.
When it is used with a
\grammarterm{template-argument-list},
as a \grammarterm{template-argument} for a type template template parameter,
or as the final identifier in the \grammarterm{elaborated-type-specifier} of
a friend class template declaration,
it is a \grammarterm{template-name} that refers to the
class template itself.
Otherwise, it is a \grammarterm{type-name}
equivalent to the \grammarterm{template-name}
followed by
the template argument list\iref{temp.decls.general,temp.arg.general}
of the class template
enclosed in \tcode{<>}.

\pnum
When the injected-class-name of a class template specialization or
partial specialization is used as a \grammarterm{type-name},
it is equivalent to the \grammarterm{template-name} followed by the
\grammarterm{template-argument}{s}
of the class template specialization or partial
specialization enclosed in
\tcode{<>}.
\begin{example}
\begin{codeblock}
template<template<class> class T> class A { };
template<class T> class Y;
template<> class Y<int> {
  Y* p;                                 // meaning \tcode{Y<int>}
  Y<char>* q;                           // meaning \tcode{Y<char>}
  A<Y>* a;                              // meaning \tcode{A<::Y>}
  class B {
    template<class> friend class Y;     // meaning \tcode{::Y}
  };
};
\end{codeblock}
\end{example}

\pnum
The injected-class-name of a class template or class
template specialization can be used as either
a \grammarterm{template-name} or a \grammarterm{type-name}
wherever it is named.
\begin{example}
\begin{codeblock}
template <class T> struct Base {
  Base* p;
};

template <class T> struct Derived: public Base<T> {
  typename Derived::Base* p;            // meaning \tcode{Derived::Base<T>}
};

template<class T, template<class> class U = T::Base> struct Third { };
Third<Derived<int> > t;                 // OK, default argument uses injected-class-name as a template
\end{codeblock}
\end{example}

\pnum
A lookup that finds an injected-class-name\iref{class.member.lookup} can result in an ambiguity in
certain cases (for example, if it is found in more than one
base class).
If all of the injected-class-names that are
found refer to specializations of the same class template,
and if the name
is used as a \grammarterm{template-name},
the reference refers to the class template itself and not a
specialization thereof, and is not ambiguous.
\begin{example}
\begin{codeblock}
template <class T> struct Base { };
template <class T> struct Derived: Base<int>, Base<char> {
  typename Derived::Base b;             // error: ambiguous
  typename Derived::Base<double> d;     // OK
};
\end{codeblock}
\end{example}

\pnum
When the normal name of the template (i.e., the name from
the enclosing scope, not the injected-class-name) is
used,
it always refers to the class template itself and not a
specialization of the template.
\begin{example}
\begin{codeblock}
template<class T> class X {
  X* p;                                 // meaning \tcode{X<T>}
  X<T>* p2;
  X<int>* p3;
  ::X* p4;                              // error: missing template argument list
                                        // \tcode{::X} does not refer to the injected-class-name
};
\end{codeblock}
\end{example}

\pnum
The name of a template parameter
shall not be bound to any following declaration
whose locus is contained by the scope
to which the template parameter belongs.
\begin{example}
\begin{codeblock}
template<class T, int i> class Y {
  int T;                                // error: template parameter hidden
  void f() {
    char T;                             // error: template parameter hidden
  }
  friend void T();                      // OK, no name bound
};

template<class X> class X;              // error: hidden by template parameter
\end{codeblock}
\end{example}

\pnum
Unqualified name lookup considers
the template parameter scope of a \grammarterm{template-declaration}
immediately after the outermost scope associated with the template declared
(even if its parent scope does not contain
the \grammarterm{template-parameter-list}).
\begin{note}
The scope of a class template,
including its non-dependent base classes\iref{temp.dep.type,class.member.lookup},
is searched before its template parameter scope.
\end{note}
\begin{example}
\begin{codeblock}
struct B { };
namespace N {
  typedef void V;
  template<class T> struct A : B {
    typedef void C;
    void f();
    template<class U> void g(U);
  };
}

template<class V> void N::A<V>::f() {   // \tcode{N::V} not considered here
  V v;                                  // \tcode{V} is still the template parameter, not \tcode{N::V}
}

template<class B> template<class C> void N::A<B>::g(C) {
  B b;                                  // \tcode{B} is the base class, not the template parameter
  C c;                                  // \tcode{C} is the template parameter, not \tcode{A}'s \tcode{C}
}
\end{codeblock}
\end{example}

\rSec2[temp.dep]{Dependent names}

\rSec3[temp.dep.general]{General}

\pnum
\indextext{dependent name|see{name, dependent}}%
Inside a template, some constructs have semantics which may differ from one
instantiation to another.
Such a construct
\defnx{depends}{name!dependent}
on the template parameters.
In particular, types and expressions may depend on the type
and/or
value of
template parameters (as determined by the template arguments) and this determines
the context for name lookup for certain names.
An expression may be
\defnx{type-dependent}{expression!type-dependent}
(that is, its type may depend on a template parameter) or
\defnx{value-dependent}{expression!value-dependent}
(that is, its value when evaluated as a constant expression\iref{expr.const.const}
may depend on a template parameter)
as described below.

\pnum
A \defnadj{dependent}{call} is an expression,
possibly formed as a non-member candidate for an operator\iref{over.match.oper},
of the form:
\begin{ncsimplebnf}
postfix-expression \terminal{(} \opt{expression-list} \terminal{)}
\end{ncsimplebnf}
where the \grammarterm{postfix-expression}
is an \grammarterm{unqualified-id} and
\begin{itemize}
\item
any of the expressions in the \grammarterm{expression-list} is a pack
expansion\iref{temp.variadic}, or
\item
any of the expressions
or \grammarterm{braced-init-list}{s}
in the
\grammarterm{expression-list}
is type-dependent\iref{temp.dep.expr}, or
\item
the \grammarterm{unqualified-id}
is a \grammarterm{template-id} in which any of the template arguments depends
on a template parameter.
\end{itemize}
The component name of an \grammarterm{unqualified-id}\iref{expr.prim.id.unqual}
is dependent if
\begin{itemize}
\item
it is a \grammarterm{conversion-function-id}
whose \grammarterm{conversion-type-id} is dependent, or
\item
it is \tcode{\keyword{operator}=} and
the current class is a templated entity, or
\item
the \grammarterm{unqualified-id} is
the \grammarterm{postfix-expression} in a dependent call.
\end{itemize}
\begin{note}
Such names
are looked up only at the point of the template instantiation\iref{temp.point}
in both the context of the template definition and the
context of the point of instantiation\iref{temp.dep.candidate}.
\end{note}

\pnum
\begin{example}
\begin{codeblock}
template<class T> struct X : B<T> {
  typename T::A* pa;
  void f(B<T>* pb) {
    static int i = B<T>::i;
    pb->j++;
  }
};
\end{codeblock}

The base class name
\tcode{B<T>},
the type name
\tcode{T::A},
the names
\tcode{B<T>::i}
and
\tcode{pb->j}
explicitly depend on the
\grammarterm{template-parameter}.
\end{example}

\rSec3[temp.dep.type]{Dependent types}

\pnum
A name or \grammarterm{template-id} refers to the
\defn{current instantiation}
if it is
\begin{itemize}
\item
in the definition of a class template, a nested class of a class template,
a member of a class template, or a member of a nested class of a class template,
the injected-class-name\iref{class.pre} of the class template or nested class,
\item
in the definition of a primary class template
or a member of a primary class template, the name of the
class template followed by the template argument list of
its \grammarterm{template-head}\iref{temp.arg} enclosed in
\tcode{<>} (or an equivalent template alias specialization),
\item
in the definition of a nested class of a class template,
the name of the nested class referenced as a member of the
current instantiation,
\item
in the definition of a class template partial specialization
or a member of a class template partial specialization, the name of
the class template followed by a template argument list
equivalent to that of the partial specialization\iref{temp.spec.partial}
enclosed in \tcode{<>} (or an equivalent template alias specialization), or
\item
in the definition of a templated function,
the name of a local class\iref{class.local}.
\end{itemize}

\pnum
A template argument that is equivalent to a template
parameter can be used in place of that
template parameter in a reference to the current instantiation.
A template argument is equivalent to a type template parameter
if it denotes the same type.
A template argument is equivalent to a constant template parameter
if it is an \grammarterm{identifier} that names a variable
that is equivalent to the template parameter.
A variable is equivalent to a template parameter if
\begin{itemize}
\item
  it has the same type as the template parameter
  (ignoring cv-qualification) and
\item
  its initializer consists of a single \grammarterm{identifier}
  that names the template parameter or, recursively, such a variable.
\end{itemize}
\begin{note}
Using a parenthesized variable name breaks the equivalence.
\end{note}
\begin{example}
\begin{codeblock}
template <class T> class A {
  A* p1;                        // \tcode{A} is the current instantiation
  A<T>* p2;                     // \tcode{A<T>} is the current instantiation
  A<T*> p3;                     // \tcode{A<T*>} is not the current instantiation
  ::A<T>* p4;                   // \tcode{::A<T>} is the current instantiation
  class B {
    B* p1;                      // \tcode{B} is the current instantiation
    A<T>::B* p2;                // \tcode{A<T>::B} is the current instantiation
    typename A<T*>::B* p3;      // \tcode{A<T*>::B} is not the current instantiation
  };
};

template <class T> class A<T*> {
  A<T*>* p1;                    // \tcode{A<T*>} is the current instantiation
  A<T>* p2;                     // \tcode{A<T>} is not the current instantiation
};

template <class T1, class T2, int I> struct B {
  B<T1, T2, I>* b1;             // refers to the current instantiation
  B<T2, T1, I>* b2;             // not the current instantiation
  typedef T1 my_T1;
  static const int my_I = I;
  static const int my_I2 = I+0;
  static const int my_I3 = my_I;
  static const long my_I4 = I;
  static const int my_I5 = (I);
  B<my_T1, T2, my_I>* b3;       // refers to the current instantiation
  B<my_T1, T2, my_I2>* b4;      // not the current instantiation
  B<my_T1, T2, my_I3>* b5;      // refers to the current instantiation
  B<my_T1, T2, my_I4>* b6;      // not the current instantiation
  B<my_T1, T2, my_I5>* b7;      // not the current instantiation
};
\end{codeblock}
\end{example}

\pnum
\indextext{dependent base class|see{base class, dependent}}%
A \defnx{dependent base class}{base class!dependent} is a base class that is a dependent type and is
not the current instantiation.
\begin{note}
A base class can be the current instantiation in the case of a nested class
naming an enclosing class as a base.
\begin{example}
\begin{codeblock}
template<class T> struct A {
  typedef int M;
  struct B {
    typedef void M;
    struct C;
  };
};

template<class T> struct A<T>::B::C : A<T> {
  M m;                          // OK, \tcode{A<T>::M}
};
\end{codeblock}
\end{example}
\end{note}

\pnum
\indextext{member of the current instantiation|see{current instantiation, member of the}}%
A qualified\iref{basic.lookup.qual} or unqualified name is a
\defnx{member of the current instantiation}{current instantiation!member of the}
if
\begin{itemize}
\item
its lookup context, if it is a qualified name,
is the current instantiation, and
\item
lookup for it finds any member of a class that is the current instantiation.
\end{itemize}
\begin{example}
\begin{codeblock}
template <class T> class A {
  static const int i = 5;
  int n1[i];                    // \tcode{i} refers to a member of the current instantiation
  int n2[A::i];                 // \tcode{A::i} refers to a member of the current instantiation
  int n3[A<T>::i];              // \tcode{A<T>::i} refers to a member of the current instantiation
  int f();
};

template <class T> int A<T>::f() {
  return i;                     // \tcode{i} refers to a member of the current instantiation
}
\end{codeblock}
\end{example}

\indextext{dependent member of the current instantiation|see{current instantiation, dependent member of the}}%
A qualified or unqualified name names a \defnx{dependent member of the current instantiation}{current instantiation!dependent member of the} if it is a
member of the current instantiation that, when looked up, refers to at least
one member declaration
(including a \grammarterm{using-declarator} whose terminal name is dependent)
of a class that is the current instantiation.

\pnum
A qualified name\iref{basic.lookup.qual} is dependent if

\begin{itemize}
\item
it is a \grammarterm{conversion-function-id}
whose \grammarterm{conversion-type-id} is dependent, or
\item
its lookup context is dependent and is not the current instantiation, or
\item
its lookup context is the current instantiation and
it is \tcode{\keyword{operator}=},
\begin{footnote}
Every instantiation of a class template declares
a different set of assignment operators.
\end{footnote}
or
\item
its lookup context is the current instantiation and
has at least one dependent base class, and
qualified name lookup for the name finds nothing\iref{basic.lookup.qual}.
\end{itemize}
\begin{example}
\begin{codeblock}
struct A {
  using B = int;
  A f();
};
struct C : A {};
template<class T>
void g(T t) {
  decltype(t.A::f())::B i;      // error: \keyword{typename} needed to interpret \tcode{B} as a type
}
template void g(C);             // \ldots even though \tcode{A} is \tcode{::A} here
\end{codeblock}
\end{example}

\pnum
If, for a given set of template arguments, a specialization of a template is
instantiated that refers to a member of the current instantiation with a
qualified name, the name is looked up in the
template instantiation context. If the result of this lookup differs from the
result of name lookup in the template definition context, name lookup is
ambiguous.
\begin{example}
\begin{codeblock}
struct A {
  int m;
};

struct B {
  int m;
};

template<typename T>
struct C : A, T {
  int f() { return this->m; }   // finds \tcode{A::m} in the template definition context
  int g() { return m; }         // finds \tcode{A::m} in the template definition context
};

template int C<B>::f();         // error: finds both \tcode{A::m} and \tcode{B::m}
template int C<B>::g();         // OK, transformation to class member access syntax
                                // does not occur in the template definition context; see~\ref{expr.prim.id.general}
\end{codeblock}
\end{example}

\pnum
An initializer is dependent if
any constituent expression\iref{intro.execution} of the initializer
is type-dependent.
A placeholder type\iref{dcl.spec.auto.general} is dependent if
it designates a type deduced from a dependent initializer.

\pnum
A placeholder for a deduced class type\iref{dcl.type.class.deduct}
is dependent if
\begin{itemize}
\item
it has a dependent initializer, or
\item
it refers to an alias template
that is a member of the current instantiation and
whose \grammarterm{defining-type-id} is dependent after
class template argument deduction\iref{over.match.class.deduct}
and substitution\iref{temp.alias}.
\end{itemize}

\pnum
\begin{example}
\begin{codeblock}
template<class T, class V>
struct S { S(T); };

template<class U>
struct A {
  template<class T> using X = S<T, U>;
  template<class T> using Y = S<T, int>;
  void f() {
    new X(1);                   // dependent
    new Y(1);                   // not dependent
  }
};
\end{codeblock}
\end{example}

\pnum
A type is dependent if it is
\begin{itemize}
\item
a template parameter,
\item
denoted by a dependent (qualified) name,
\item
a nested class or enumeration that is a direct member of
a class that is the current instantiation,
\item
a cv-qualified type where the cv-unqualified type is dependent,
\item
a compound type constructed from any dependent type,
\item
an array type whose element type is dependent or whose
bound (if any) is value-dependent,
\item
a function type whose parameters include one or more function parameter packs,
\item
a function type whose exception specification is value-dependent,
\item
denoted by a dependent placeholder type,
\item
denoted by a dependent placeholder for a deduced class type,
\item
denoted by a \grammarterm{simple-template-id}
in which either the template name is a template parameter or any of the
template arguments is dependent\iref{temp.dep.temp},
\begin{footnote}
This includes an injected-class-name\iref{class.pre} of a class template
used without a \grammarterm{template-argument-list}.
\end{footnote}
\item a \grammarterm{pack-index-specifier},
\item denoted by \tcode{decltype(}\grammarterm{expression}{}\tcode{)},
where \grammarterm{expression} is type-dependent\iref{temp.dep.expr}, or
\item denoted by a \grammarterm{splice-type-specifier} in which either
the \grammarterm{splice-specifier} or
\grammarterm{splice-specialization-specifier}
is dependent\iref{temp.dep.splice}.
\end{itemize}

\pnum
\begin{note}
Because typedefs do not introduce new types, but
instead simply refer to other types, a name that refers to a
typedef that is a member of the current instantiation is dependent
only if the type referred to is dependent.
\end{note}

\rSec3[temp.dep.expr]{Type-dependent expressions}

\pnum
Except as described below, an expression is type-dependent if any
subexpression is type-dependent.

\pnum
\keyword{this}
is type-dependent if the current class\iref{expr.prim.this} is
dependent\iref{temp.dep.type}.

\pnum
An \grammarterm{id-expression} is type-dependent
if it is a \grammarterm{template-id} that is not a concept-id and is dependent;
or if its terminal name is
\begin{itemize}
\item
associated by name lookup with one or more declarations
declared with a dependent type,
\item
associated by name lookup with
a constant template parameter
declared with a type
that contains a placeholder type\iref{dcl.spec.auto},
\item
associated by name lookup with
a variable declared with a type that contains a placeholder type\iref{dcl.spec.auto}
where the initializer is type-dependent,
\item
associated by name lookup with one or more
declarations of member functions of a class that is the current instantiation
declared with a return type that contains a placeholder type,
\item
associated by name lookup with
a structured binding declaration\iref{dcl.struct.bind} whose
\grammarterm{brace-or-equal-initializer} is type-dependent,
\item
associated by name lookup with a structured binding pack,
\begin{example}
\begin{codeblock}
struct C { };

void g(...);            // \#1

template <typename T>
void f() {
  C arr[1];
  auto [...e] = arr;
  g(e...);              // calls \#2
}

void g(C);              // \#2

int main() {
  f<int>();
}
\end{codeblock}
\end{example}
\item
associated by name lookup with
an entity captured by copy\iref{expr.prim.lambda.capture}
in a \grammarterm{lambda-expression}
that has an explicit object parameter whose type is dependent\iref{dcl.fct},
\item
the
\grammarterm{identifier}
\mname{func}\iref{dcl.fct.def.general}, where any enclosing function is a
template, a member of a class template, or a generic lambda,
\item
associated by name lookup
with a result binding\iref{dcl.contract.res} of a function
whose return type is dependent,
\item
a \grammarterm{conversion-function-id} that specifies a dependent type,
\item
a name $N$ introduced by the \grammarterm{for-range-declaration}
of an \grammarterm{expansion-statement} $S$
if the type specified for $N$ contains a placeholder type and either
\begin{itemize}
\item $S$ is not an iterating expansion statement or
\item the \grammarterm{expansion-initializer} of $S$ is type-dependent, or
\end{itemize}
\item
dependent
\end{itemize}
or if it names a dependent member of the current instantiation that is a static
data member of type
``array of unknown bound of \tcode{T}'' for some \tcode{T}\iref{temp.static}.
Expressions of the following forms are type-dependent only if the type
specified by the
\grammarterm{type-id},
\grammarterm{simple-type-specifier},
\grammarterm{typename-specifier},
or
\grammarterm{new-type-id}
is dependent, even if any subexpression is type-dependent:

\begin{ncsimplebnf}
simple-type-specifier \terminal{(} \opt{expression-list} \terminal{)}\br
simple-type-specifier braced-init-list\br
typename-specifier \terminal{(} \opt{expression-list} \terminal{)}\br
typename-specifier braced-init-list\br
\opt{\terminal{::}} \keyword{new} \opt{new-placement} new-type-id \opt{new-initializer}\br
\opt{\terminal{::}} \keyword{new} \opt{new-placement} \terminal{(} type-id \terminal{)} \opt{new-initializer}\br
\keyword{dynamic_cast} \terminal{<} type-id \terminal{>} \terminal{(} expression \terminal{)}\br
\keyword{static_cast} \terminal{<} type-id \terminal{>} \terminal{(} expression \terminal{)}\br
\keyword{const_cast} \terminal{<} type-id \terminal{>} \terminal{(} expression \terminal{)}\br
\keyword{reinterpret_cast} \terminal{<} type-id \terminal{>} \terminal{(} expression \terminal{)}\br
\terminal{(} type-id \terminal{)} cast-expression
\end{ncsimplebnf}

\pnum
Expressions of the following forms are never type-dependent (because the type
of the expression cannot be dependent):

\begin{ncsimplebnf}
literal\br
\keyword{sizeof} unary-expression\br
\keyword{sizeof} \terminal{(} type-id \terminal{)}\br
\keyword{sizeof} \terminal{...} \terminal{(} identifier \terminal{)}\br
\keyword{alignof} \terminal{(} type-id \terminal{)}\br
\keyword{typeid} \terminal{(} expression \terminal{)}\br
\keyword{typeid} \terminal{(} type-id \terminal{)}\br
\opt{\terminal{::}} \keyword{delete} cast-expression\br
\opt{\terminal{::}} \keyword{delete} \terminal{[} \terminal{]} cast-expression\br
\keyword{throw} \opt{assignment-expression}\br
\keyword{noexcept} \terminal{(} expression \terminal{)}\br
requires-expression\br
reflect-expression
\end{ncsimplebnf}

\begin{note}
For the standard library macro \tcode{offsetof},
see~\ref{support.types}.
\end{note}

\pnum
A class member access expression\iref{expr.ref} is
type-dependent if
\begin{itemize}
\item
the terminal name of its \grammarterm{id-expression}, if any, is dependent,
\item
its \grammarterm{splice-expression}, if any, is type-dependent, or
\item
the expression refers to a member of the current instantiation and
the type of the referenced member is dependent.
\end{itemize}
\begin{note}
In an expression of the form
\tcode{x.y}
or
\tcode{xp->y}
the type of the expression is usually the type of the member
\tcode{y}
of the class of
\tcode{x}
(or the class pointed to by
\tcode{xp}).
However, if
\tcode{x}
or
\tcode{xp}
refers to a dependent type that is not the current instantiation,
the type of
\tcode{y}
is always dependent.
\end{note}

\pnum
A \grammarterm{braced-init-list} is type-dependent if any element is
type-dependent or is a pack expansion.

\pnum
A \grammarterm{fold-expression} is type-dependent.

\pnum
A \grammarterm{pack-index-expression} is type-dependent
if its \grammarterm{id-expression} is type-dependent.

\pnum
A \grammarterm{splice-expression} is type-dependent
if its \grammarterm{splice-specifier} or
\grammarterm{splice-specialization-specifier}
is dependent\iref{temp.dep.splice}.

\rSec3[temp.dep.constexpr]{Value-dependent expressions}

\pnum
Except as described below, an expression used in a context where a
constant expression is required is value-dependent if any
subexpression is value-dependent.

\pnum
An
\grammarterm{id-expression}
is value-dependent if
\begin{itemize}
\item
it is a concept-id and
its \grammarterm{concept-name} is dependent or
any of its arguments are dependent\iref{temp.dep.temp},
\item
it is type-dependent,
\item
it is the name of a constant template parameter,
\item
it is a name introduced by the \grammarterm{for-range-declaration}
of an \grammarterm{expansion-statement}\iref{stmt.expand},
\item
it names a static data member that is a dependent member of the current
instantiation and is not initialized in a \grammarterm{member-declarator},
\item
it names a static member function that is a dependent member of the current
instantiation, or
\item
it names a potentially-constant variable\iref{expr.const.init}
that is initialized with an expression that is value-dependent.
\end{itemize}

Expressions of the following form are value-dependent if the
\grammarterm{unary-expression} or \grammarterm{expression}
is type-dependent or the
\grammarterm{type-id}
is dependent:

\begin{ncsimplebnf}
\keyword{sizeof} unary-expression\br
\keyword{sizeof} \terminal{(} type-id \terminal{)}\br
\keyword{typeid} \terminal{(} expression \terminal{)}\br
\keyword{typeid} \terminal{(} type-id \terminal{)}\br
\keyword{alignof} \terminal{(} type-id \terminal{)}
\end{ncsimplebnf}

\begin{note}
For the standard library macro \tcode{offsetof},
see~\ref{support.types}.
\end{note}

\pnum
Expressions of the following form are value-dependent if either the
\grammarterm{type-id},
\grammarterm{simple-type-specifier}, or
\grammarterm{typename-specifier}
is dependent or the
\grammarterm{expression}
or
\grammarterm{cast-expression}
is value-dependent or
any \grammarterm{expression} in the \grammarterm{expression-list}
is value-dependent or
any \grammarterm{assignment-expression} in the \grammarterm{braced-init-list}
is value-dependent:

\begin{ncsimplebnf}
simple-type-specifier \terminal{(} \opt{expression-list} \terminal{)}\br
typename-specifier \terminal{(} \opt{expression-list} \terminal{)}\br
simple-type-specifier braced-init-list\br
typename-specifier braced-init-list\br
\keyword{static_cast} \terminal{<} type-id \terminal{>} \terminal{(} expression \terminal{)}\br
\keyword{const_cast} \terminal{<} type-id \terminal{>} \terminal{(} expression \terminal{)}\br
\keyword{reinterpret_cast} \terminal{<} type-id \terminal{>} \terminal{(} expression \terminal{)}\br
\keyword{dynamic_cast} \terminal{<} type-id \terminal{>} \terminal{(} expression \terminal{)}\br
\terminal{(} type-id \terminal{)} cast-expression
\end{ncsimplebnf}

\pnum
Expressions of the following form are value-dependent:

\begin{ncsimplebnf}
\keyword{sizeof} \terminal{...} \terminal{(} identifier \terminal{)}\br
fold-expression
\end{ncsimplebnf}

\pnum
A \grammarterm{noexcept-expression}\iref{expr.unary.noexcept}
is value-dependent if
its \grammarterm{expression} involves a template parameter.

\pnum
An expression of the form \tcode{\&}\grammarterm{qualified-id} where the
\grammarterm{qualified-id} names a dependent member of the current
instantiation is value-dependent.
An expression of the form \tcode{\&}\grammarterm{cast-expression}
is also value-dependent if evaluating \grammarterm{cast-expression}
as a core constant expression\iref{expr.const.core} succeeds and
the result of the evaluation refers to a templated entity
that is an object with static or thread storage duration or a member function.

\pnum
A \grammarterm{reflect-expression} is value-dependent if
\begin{itemize}
\item
it is of the form \tcode{\caret\caret \grammarterm{reflection-name}} and
the \grammarterm{reflection-name}
\begin{itemize}
\item is a dependent qualified name,
\item is a dependent \grammarterm{namespace-name},
\item is the name of a template parameter, or
\item names a dependent member of the current instantiation\iref{temp.dep.type},
\end{itemize}
\item
it is of the form \tcode{\caret\caret \grammarterm{type-id}} and
the \grammarterm{type-id} denotes a dependent type, or
\item
it is of the form \tcode{\caret\caret \grammarterm{id-expression}} and
the \grammarterm{id-expression} is value-dependent.
\end{itemize}

\pnum
A \grammarterm{splice-expression} is value-dependent
if its \grammarterm{splice-specifier} or
\grammarterm{splice-specialization-specifier}
is dependent\iref{temp.dep.splice}.

\rSec3[temp.dep.splice]{Dependent splice specifiers}

\pnum
A \grammarterm{splice-specifier} is dependent
if its converted \grammarterm{constant-expression} is value-dependent.
A \grammarterm{splice-specialization-specifier} is dependent
if its \grammarterm{splice-specifier} is dependent or
if any of its template arguments are dependent.
A \grammarterm{splice-scope-specifier} is dependent
if its \grammarterm{splice-specifier} or
\grammarterm{splice-specialization-specifier} is dependent.

\pnum
\begin{example}
\begin{codeblock}
template<auto T, auto NS>
void fn() {
  using a = [:T:]<1>;                           // \tcode{[:T:]<1>} is dependent because \tcode{[:T:]} is dependent
  static_assert([:NS:]::template TCls<1>::v == a::v);   // \tcode{[:NS:]} is dependent
}

namespace N {
  template <auto V> struct TCls { static constexpr int v = V; };
}

int main() {
  fn<^^N::TCls, ^^N>();
}
\end{codeblock}
\end{example}

\pnum
\begin{example}
\begin{codeblock}
template<template<class> class X>
struct S {
  [:^^X:]<int, float> m;
};

template<class> struct V1 {};
template<class, class = int> struct V2 {};

S<V1> s1;                       // error: \tcode{V1<int, float>} has too many template arguments
S<V2> s2;                       // OK
\end{codeblock}
\end{example}

\rSec3[temp.dep.namespace]{Dependent namespaces}

\pnum
A namespace alias is dependent
if it is introduced by a \grammarterm{namespace-alias-definition}
whose \grammarterm{qualified-namespace-specifier} (if any) is
a dependent qualified name or
whose \grammarterm{splice-specifier} (if any) is dependent.
A \grammarterm{namespace-name} is dependent
if it names a dependent namespace alias.

\pnum
\begin{example}
\begin{codeblock}
template<std::meta::info R>
int fn() {
  namespace Alias = [:R:];          // \tcode{[:R:]} is dependent
  return typename Alias::T{};       // \tcode{Alias} is dependent
}

namespace NS {
  using T = int;
}

int a = fn<^^NS>();
\end{codeblock}
\end{example}

\rSec3[temp.dep.temp]{Dependent template arguments}

\pnum
A type
\grammarterm{template-argument}
is dependent if the type it specifies is dependent.

\pnum
A constant
\grammarterm{template-argument}
is dependent if its type is dependent or the constant
expression it specifies is value-dependent.

\pnum
Furthermore, a constant
\grammarterm{template-argument}
is dependent if the corresponding constant template parameter
is of reference or pointer type and the \grammarterm{template-argument}
designates or points to a member of the current instantiation or a member of
a dependent type.

\pnum
%FIXME: "also" adds nothing here and reads like a note; remove it?
A template argument is also dependent if it is a pack expansion.

\pnum
A template template argument is dependent if
it names a template parameter or
its terminal name is dependent.

\rSec2[temp.dep.res]{Dependent name resolution}
\rSec3[temp.point]{Point of instantiation}

\pnum
\indextext{instantiation!point of}%
For a function template specialization, a member function template
specialization, or a specialization for a member function or static data member
of a class template,
the point of instantiation of the specialization is the point of instantiation
of the enclosing specialization if
\begin{itemize}
\item the specialization is implicitly instantiated
because it is referenced from within another template specialization and
\item the context from which it is referenced depends on a template parameter.
\end{itemize}
Otherwise, the point of instantiation for such a specialization immediately
follows the namespace scope declaration
or definition that refers to the specialization.

\pnum
If a function template or member function of a class template is called
in a way which uses the definition of a default argument of that function
template or member function,
the point of instantiation of the default argument is the point of
instantiation of the function template or member function specialization.

\pnum
For a \grammarterm{noexcept-specifier} of a function template
specialization or specialization of a member function of a class template,
the point of instantiation of the
\grammarterm{noexcept-specifier} is the point of instantiation of the
specialization that requires it if
\begin{itemize}
\item the \grammarterm{noexcept-specifier} is implicitly instantiated
because it is needed by another template specialization and
\item the context that requires it depends on a template parameter.
\end{itemize}
Otherwise, the point of instantiation for such
a \grammarterm{noexcept-specifier} immediately follows the namespace
scope declaration or definition that requires the
\grammarterm{noexcept-specifier}.

\pnum
For a class template specialization, a class member template specialization,
or a specialization for a class member of a class template,
the point of instantiation is immediately before the point of instantiation of
the enclosing template if
\begin{itemize}
\item the specialization is implicitly instantiated
because it is referenced from within another template specialization,
\item the context from which the specialization is referenced
depends on a template parameter, and
\item the specialization is not instantiated
previous to the instantiation of the enclosing template.
\end{itemize}
Otherwise, the point of instantiation for such a specialization immediately
precedes the namespace scope declaration
or definition that refers to the specialization.

\pnum
If a virtual function is implicitly instantiated, its point of instantiation
is immediately following the point of instantiation of its enclosing class
template specialization.

\pnum
An explicit instantiation definition is an instantiation
point for the specialization or specializations specified by the explicit
instantiation.

\pnum
A specialization for a function template, a member function template,
or of a member function or static data member of a class template may have
multiple points of instantiations within a translation unit, and in addition
to the points of instantiation described above,
\begin{itemize}
\item
for any such
specialization that has a point of instantiation within the
\grammarterm{declaration-seq} of the
\grammarterm{translation-unit},
prior to the \grammarterm{private-module-fragment} (if any),
the point after the \grammarterm{declaration-seq}
of the \grammarterm{translation-unit}
is also considered a point of instantiation,
and
\item
for any such specialization that has a point of instantiation
within the \grammarterm{private-module-fragment},
the end of the translation unit is also
considered a point of instantiation.
\end{itemize}
A specialization for a class template has at most one point of instantiation
within a translation unit.
A specialization for any template may have points of instantiation in multiple
translation units.
If two different points of instantiation give a template specialization
different meanings according to the one-definition rule\iref{basic.def.odr},
the program is ill-formed, no diagnostic required.

\pnum
For the \grammarterm{compound-statement}
of an \grammarterm{expansion-statement}\iref{stmt.expand},
the point of instantiation is the point of instantiation
of its enclosing templated entity, if any.
Otherwise, it immediately follows the namespace-scope declaration
or definition that contains the expansion statement.

\rSec3[temp.dep.candidate]{Candidate functions}

\pnum
\indextext{functions!candidate}%
If a dependent call\iref{temp.dep} would be ill-formed or
would find a better match had the lookup for its dependent name
considered all the function declarations with external linkage
introduced in the associated namespaces in all translation units,
not just considering those declarations found in the template definition and
template instantiation contexts\iref{basic.lookup.argdep},
then the program is ill-formed, no diagnostic required.

\pnum
\begin{example}
\begin{codeblocktu}{Source file \tcode{"X.h"}}
namespace Q {
  struct X { };
}
\end{codeblocktu}

\begin{codeblocktu}{Source file \tcode{"G.h"}}
namespace Q {
  void g_impl(X, X);
}
\end{codeblocktu}

\begin{codeblocktu}{Module interface unit of \tcode{M1}}
module;
#include "X.h"
#include "G.h"
export module M1;
export template<typename T>
void g(T t) {
  g_impl(t, Q::X{ });   // ADL in definition context finds \tcode{Q::g_impl}, \tcode{g_impl} not discarded
}
\end{codeblocktu}

\begin{codeblocktu}{Module interface unit of \tcode{M2}}
module;
#include "X.h"
export module M2;
import M1;
void h(Q::X x) {
   g(x);                // OK
}
\end{codeblocktu}
\end{example}

\pnum
\begin{example}
\begin{codeblocktu}{Module interface unit of \tcode{Std}}
export module Std;
export template<typename Iter>
void indirect_swap(Iter lhs, Iter rhs)
{
  swap(*lhs, *rhs);     // \tcode{swap} not found by unqualified lookup, can be found only via ADL
}
\end{codeblocktu}

\begin{codeblocktu}{Module interface unit of \tcode{M}}
export module M;
import Std;

struct S { /* ...*/ };
void swap(S&, S&);      // \#1

void f(S* p, S* q)
{
  indirect_swap(p, q);  // finds \#1 via ADL in instantiation context
}
\end{codeblocktu}
\end{example}

\pnum
\begin{example}
\begin{codeblocktu}{Source file \tcode{"X.h"}}
struct X { /* ... */ };
X operator+(X, X);
\end{codeblocktu}

\begin{codeblocktu}{Module interface unit of \tcode{F}}
export module F;
export template<typename T>
void f(T t) {
  t + t;
}
\end{codeblocktu}

\begin{codeblocktu}{Module interface unit of \tcode{M}}
module;
#include "X.h"
export module M;
import F;
void g(X x) {
  f(x);             // OK, instantiates \tcode{f} from \tcode{F},
                    // \tcode{operator+} is visible in instantiation context
}
\end{codeblocktu}
\end{example}

\pnum
\begin{example}
\begin{codeblocktu}{Module interface unit of \tcode{A}}
export module A;
export template<typename T>
void f(T t) {
  cat(t, t);            // \#1
  dog(t, t);            // \#2
}
\end{codeblocktu}

\begin{codeblocktu}{Module interface unit of \tcode{B}}
export module B;
import A;
export template<typename T, typename U>
void g(T t, U u) {
  f(t);
}
\end{codeblocktu}

\begin{codeblocktu}{Source file \tcode{"foo.h"}, not an importable header}
struct foo {
  friend int cat(foo, foo);
};
int dog(foo, foo);
\end{codeblocktu}

\begin{codeblocktu}{Module interface unit of \tcode{C1}}
module;
#include "foo.h"        // \tcode{dog} not referenced, discarded
export module C1;
import B;
export template<typename T>
void h(T t) {
  g(foo{ }, t);
}
\end{codeblocktu}

\begin{codeblocktu}{Translation unit}
import C1;
void i() {
   h(0);                // error: \tcode{dog} not found at \#2
}
\end{codeblocktu}

\begin{codeblocktu}{Importable header \tcode{"bar.h"}}
struct bar {
  friend int cat(bar, bar);
};
int dog(bar, bar);
\end{codeblocktu}

\begin{codeblocktu}{Module interface unit of \tcode{C2}}
module;
#include "bar.h"        // imports header unit \tcode{"bar.h"}
export module C2;
import B;
export template<typename T>
void j(T t) {
  g(bar{ }, t);
}
\end{codeblocktu}

\begin{codeblocktu}{Translation unit}
import C2;
void k() {
   j(0);                // OK, \tcode{dog} found in instantiation context:
                        // visible at end of module interface unit of \tcode{C2}
}
\end{codeblocktu}
\end{example}

\rSec1[temp.spec]{Template instantiation and specialization}

\rSec2[temp.spec.general]{General}

\pnum
\indextext{specialization!template}%
The act of instantiating a function, a variable,
a class, a member of a class template, or
a member template is referred to as
\defn{template instantiation}.

\pnum
A function instantiated from a function template is called an instantiated
function.
A class instantiated from a class template is called an instantiated class.
A member function, a member class, a member enumeration, or a static data member of a class template
instantiated from the member definition of the class template is called,
respectively, an instantiated member function, member class, member enumeration, or static data
member.
A member function instantiated from a member function template is called an
instantiated member function.
A member class instantiated from a member class template is called an
instantiated member class.
A variable instantiated from a variable template is called an
instantiated variable.
A static data member instantiated from a static data member template
is called an instantiated static data member.

\pnum
An explicit specialization may be declared for a function template,
a variable template, a class template, a member of a class template, or
a member template.
An explicit specialization declaration is introduced by
\tcode{\keyword{template}<>}.
In an explicit specialization declaration for
a variable template, a class template,
a member of a class template, or a class member template,
the variable or class that is explicitly specialized
shall be specified with a \grammarterm{simple-template-id}.
In the explicit specialization declaration for a function template,
the function explicitly specialized may be specified using a \grammarterm{template-id}.
\begin{example}
\begin{codeblock}
template<class T = int> struct A {
  static int x;
};
template<class U> void g(U) { }

template<> struct A<double> { };        // specialize for \tcode{T == double}
template<> struct A<> { };              // specialize for \tcode{T == int}
template<> void g(char) { }             // specialize for \tcode{U == char}
                                        // \tcode{U} is deduced from the parameter type
template<> void g<int>(int) { }         // specialize for \tcode{U == int}
template<> int A<char>::x = 0;          // specialize for \tcode{T == char}

template<class T = int> struct B {
  static int x;
};
template<> int B<>::x = 1;              // specialize for \tcode{T == int}
\end{codeblock}
\end{example}

\pnum
An instantiated template specialization can be either implicitly
instantiated\iref{temp.inst} for a given argument list or be explicitly
instantiated\iref{temp.explicit}.
A \defn{specialization} is a class, variable, function, or class member that is either
instantiated\iref{temp.inst} from a templated entity or is an
explicit specialization\iref{temp.expl.spec} of a templated entity.

\pnum
For a given template and a given set of
\grammarterm{template-argument}{s},
\begin{itemize}
\item
an explicit instantiation definition shall appear at most once in a program,
\item
an explicit specialization shall be defined at most once
in a program, as specified in \ref{basic.def.odr}, and
\item
both an explicit instantiation and a declaration of an
explicit specialization shall not appear in a program unless
the explicit specialization is reachable from the explicit instantiation.
\end{itemize}
An implementation is not required to diagnose a violation of this rule
if neither declaration is reachable from the other.

\pnum
The usual access checking rules do not apply to names
in a declaration of an explicit instantiation or explicit specialization,
with the exception of names appearing in a function body,
default argument, \grammarterm{base-clause}, \grammarterm{member-specification}, \grammarterm{enumerator-list},
or static data member or variable template initializer.
\begin{note}
In particular, the template arguments and names
used in the function declarator
(including parameter types, return types and exception specifications)
can be private types or objects that would normally not be accessible.
\end{note}

\pnum
Each class template specialization instantiated from a template has its own
copy of any static members.
\begin{example}
\begin{codeblock}
template<class T> class X {
  static T s;
};
template<class T> T X<T>::s = 0;
X<int> aa;
X<char*> bb;
\end{codeblock}

\tcode{X<int>}
has a static member
\tcode{s}
of type
\tcode{int}
and
\tcode{X<char*>}
has a static member
\tcode{s}
of type
\tcode{char*}.
\end{example}

\pnum
If a function declaration acquired its function type through
a dependent type\iref{temp.dep.type} without using the syntactic form of
a function declarator, the program is ill-formed.
\begin{example}
\begin{codeblock}
template<class T> struct A {
  static T t;
};
typedef int function();
A<function> a;      // error: would declare \tcode{A<function>::t} as a static member function
\end{codeblock}
\end{example}

\rSec2[temp.inst]{Implicit instantiation}

\pnum
A template specialization $E$ is a \defnadj{declared}{specialization}
if there is a reachable
explicit instantiation definition\iref{temp.explicit} or
explicit specialization declaration\iref{temp.expl.spec}
for $E$, or
if there is a reachable explicit instantiation declaration for $E$ and
$E$ is not
\begin{itemize}
\item
an inline function,
\item
declared with a type deduced
from its initializer or return value\iref{dcl.spec.auto},
\item
a potentially-constant variable\iref{expr.const.init}, or
\item
a specialization of a templated class.
\end{itemize}
\begin{note}
An implicit instantiation in an importing translation unit
cannot use names with internal linkage
from an imported translation unit\iref{basic.link}.
\end{note}

\pnum
\indextext{instantiation!template implicit}%
Unless a class template specialization is a declared specialization,
the class template specialization is implicitly instantiated when the
specialization is referenced in a context that requires a completely-defined
object type or when the completeness of the class type affects the semantics
of the program.
\begin{note}
In particular, if the semantics of an expression depend on the member or
base class lists of a class template specialization, the class template
specialization is implicitly generated. For instance, deleting a pointer
to class type depends on whether or not the class declares a destructor,
and a conversion between pointers to class type depends on the
inheritance relationship between the two classes involved.
\end{note}
\begin{example}
\begin{codeblock}
template<class T> class B { @\commentellip@ };
template<class T> class D : public B<T> { @\commentellip@ };

void f(void*);
void f(B<int>*);

void g(D<int>* p, D<char>* pp, D<double>* ppp) {
  f(p);             // instantiation of \tcode{D<int>} required: call \tcode{f(B<int>*)}
  B<char>* q = pp;  // instantiation of \tcode{D<char>} required: convert \tcode{D<char>*} to \tcode{B<char>*}
  delete ppp;       // instantiation of \tcode{D<double>} required
}
\end{codeblock}
\end{example}
If the template selected for the specialization\iref{temp.spec.partial.match}
has been declared, but not defined,
at the point of instantiation\iref{temp.point},
the instantiation yields an incomplete class type\iref{term.incomplete.type}.
\begin{example}
\begin{codeblock}
template<class T> class X;
X<char> ch;         // error: incomplete type \tcode{X<char>}
\end{codeblock}
\end{example}
\begin{note}
Within a template declaration,
a local class\iref{class.local} or enumeration and the members of
a local class are never considered to be entities that can be separately
instantiated (this includes their default arguments,
\grammarterm{noexcept-specifier}{s}, and non-static data member
initializers, if any,
but not their \grammarterm{type-constraint}{s} or \grammarterm{requires-clause}{s}).
As a result, the dependent names are looked up, the
semantic constraints are checked, and any templates used are instantiated as
part of the instantiation of the entity within which the local class or
enumeration is declared.
\end{note}

\pnum
The implicit instantiation of a class template specialization causes
\begin{itemize}
\item
  the implicit instantiation of the declarations, but not of the definitions,
  of the non-deleted
  class member functions,
  member classes,
  scoped member enumerations,
  static data members,
  member templates, and
  friends; and
\item
  the implicit instantiation of the definitions of
  deleted member functions,
  unscoped member enumerations, and
  member anonymous unions.
\end{itemize}
The implicit instantiation of a class template specialization
does not cause the implicit instantiation of
default arguments or \grammarterm{noexcept-specifier}{s}
of the class member functions.
\begin{example}
\begin{codeblock}
template<class T>
struct C {
  void f() { T x; }
  void g() = delete;
};
C<void> c;                      // OK, definition of \tcode{C<void>::f} is not instantiated at this point
template<> void C<int>::g() { } // error: redefinition of \tcode{C<int>::g}
\end{codeblock}
\end{example}
However, for the purpose of determining whether an instantiated redeclaration
is valid according to~\ref{basic.def.odr} and \ref{class.mem},
an instantiated declaration that corresponds to a definition in the template
is considered to be a definition.
\begin{example}
\begin{codeblock}
template<class T, class U>
struct Outer {
  template<class X, class Y> struct Inner;
  template<class Y> struct Inner<T, Y>;         // \#1a
  template<class Y> struct Inner<T, Y> { };     // \#1b; OK, valid redeclaration of \#1a
  template<class Y> struct Inner<U, Y> { };     // \#2
};

Outer<int, int> outer;                          // error at \#2
\end{codeblock}

\tcode{Outer<int, int>::Inner<int, Y>} is redeclared at \#1b. (It is not defined
but noted as being associated with a definition in \tcode{Outer<T, U>}.) \#2
is also a redeclaration of \#1a. It is noted as associated with a definition,
so it is an invalid redeclaration of the same partial specialization.

\begin{codeblock}
template<typename T> struct Friendly {
  template<typename U> friend int f(U) { return sizeof(T); }
};
Friendly<char> fc;
Friendly<float> ff;                             // error: produces second definition of \tcode{f(U)}
\end{codeblock}
\end{example}

\pnum
Unless a member of a templated class is a declared specialization,
the specialization of the member is implicitly instantiated when the
specialization is referenced in a context that requires the member definition
to exist or
if the existence of the definition of the member
affects the semantics of the program;
in particular, the initialization (and any associated side effects) of a
static data member does not occur unless the static data member is itself used
in a way that requires the definition of the static data member to exist.

\pnum
Unless a function template specialization is a declared specialization,
the function template specialization is implicitly instantiated when the
specialization is referenced in a context that requires a function definition
to exist or
if the existence of the definition affects the semantics of the program.
A function whose declaration was instantiated from a friend function definition is
implicitly instantiated when it is referenced in a context that
requires a function definition to exist or
if the existence of the definition affects the semantics of the program.
Unless a call is to a function template explicit specialization or
to a member function of an explicitly specialized class template,
a default argument for a function template or a member function of a
class template is implicitly instantiated when the function is
called in a context that requires the value of the default argument.
\begin{note}
An inline function
that is the subject of an explicit instantiation declaration
is not a declared specialization;
the intent is that it still be implicitly instantiated
when odr-used\iref{term.odr.use}
so that the body can be considered for inlining,
but that no out-of-line copy of it be generated in the translation unit.
\end{note}

\pnum
\begin{example}
\begin{codeblock}
template<class T> struct Z {
  void f();
  void g();
};

void h() {
  Z<int> a;         // instantiation of class \tcode{Z<int>} required
  Z<char>* p;       // instantiation of class \tcode{Z<char>} not required
  Z<double>* q;     // instantiation of class \tcode{Z<double>} not required

  a.f();            // instantiation of \tcode{Z<int>::f()} required
  p->g();           // instantiation of class \tcode{Z<char>} required, and
                    // instantiation of \tcode{Z<char>::g()} required
}
\end{codeblock}

Nothing in this example requires
\keyword{class}
\tcode{Z<double>},
\tcode{Z<int>::g()},
or
\tcode{Z<char>::f()}
to be implicitly instantiated.
\end{example}

\pnum
Unless a variable template specialization is a declared specialization,
the variable template specialization is implicitly instantiated
when it is referenced in a context
that requires a variable definition to exist or
if the existence of the definition affects the semantics of the program.
A default template argument for a variable template is implicitly instantiated
when the variable template is referenced in a context
that requires the value of the default argument.

\pnum
\indextext{definition!program semantics affected by}%
\indextext{variable!program semantics affected by the existence of a variable definition}%
\indextext{function!program semantics affected by the existence of a function definition}%
\indextext{program semantics!affected by the existence of a variable or function definition}%
The existence of a definition of a variable or function
is considered to affect the semantics of the program
if the variable or function
is needed for constant evaluation by an expression\iref{expr.const.defns},
even if constant evaluation of the expression is not required or
if constant expression evaluation does not use the definition.

\begin{example}
\begin{codeblock}
template<typename T> constexpr int f() { return T::value; }
template<bool B, typename T> void g(decltype(B ? f<T>() : 0));
template<bool B, typename T> void g(...);
template<bool B, typename T> void h(decltype(int{B ? f<T>() : 0}));
template<bool B, typename T> void h(...);
void x() {
  g<false, int>(0); // OK, \tcode{B ? f<T>() :\ 0} is not potentially constant evaluated
  h<false, int>(0); // error, instantiates \tcode{f<int>} even though \tcode{B} evaluates to \tcode{false} and
                    // list-initialization of \tcode{int} from \tcode{int} cannot be narrowing
}
\end{codeblock}
\end{example}

\pnum
If the function selected by overload resolution\iref{over.match}
can be determined without instantiating a class template definition,
it is unspecified whether that instantiation actually takes place.
\begin{example}
\begin{codeblock}
template <class T> struct S {
  operator int();
};

void f(int);
void f(S<int>&);
void f(S<float>);

void g(S<int>& sr) {
  f(sr);            // instantiation of \tcode{S<int>} allowed but not required
                    // instantiation of \tcode{S<float>} allowed but not required
};
\end{codeblock}
\end{example}

\pnum
If a function template specialization is used in
a way that involves overload resolution,
a declaration of the specialization is implicitly instantiated\iref{temp.over}.

\pnum
An implementation shall not implicitly instantiate a function template,
a variable template,
a member template, a non-virtual member function, a member class or
static data member of a templated class, or a substatement of a constexpr if
statement\iref{stmt.if}, unless such instantiation is required.
\begin{note}
The instantiation of a generic lambda
does not require instantiation of
substatements of a constexpr if statement
within its \grammarterm{compound-statement}
unless the call operator template is instantiated.
\end{note}
It is unspecified whether or not an implementation implicitly instantiates a
virtual member function of a class template if the virtual member function would
not otherwise be instantiated.
The use of a template specialization in
a default argument or default member initializer
shall not cause the template to be implicitly instantiated except
where needed to determine
the correctness of the default argument or default member initializer.
The use of a default argument in a
function call causes specializations in the default argument to be implicitly
instantiated.
Similarly, the use of a default member initializer
in a constructor definition or an aggregate initialization
causes specializations in the default member initializer to be instantiated.

\pnum
If a templated function
\tcode{f}
is called in a way that requires a default argument to be used,
the dependent names are looked up, the semantics constraints are checked,
and the instantiation of any template used in the default argument
is done as if the default argument had been
an initializer used in a function template specialization with the same scope,
the same template parameters and the same access as that of the function template
\tcode{f}
used at that point, except that the scope in which a closure type is
declared\iref{expr.prim.lambda.closure} --- and therefore its associated namespaces ---
remain as determined from the context of the definition for the default
argument.
This analysis is called
\defn{default argument instantiation}.
The instantiated default argument is then used as the argument of
\tcode{f}.

\pnum
Each default argument is instantiated independently.
\begin{example}
\begin{codeblock}
template<class T> void f(T x, T y = ydef(T()), T z = zdef(T()));

class  A { };

A zdef(A);

void g(A a, A b, A c) {
  f(a, b, c);       // no default argument instantiation
  f(a, b);          // default argument \tcode{z = zdef(T())} instantiated
  f(a);             // error: \tcode{ydef} is not declared
}
\end{codeblock}
\end{example}

\pnum
The \grammarterm{noexcept-specifier} and \grammarterm{function-contract-specifier}s
of a function template specialization
are not instantiated along with the function declaration;
they are instantiated
when needed\iref{except.spec,dcl.contract.func}. If such a
specifier is needed but has not yet been
instantiated, the dependent names are looked up, the semantics constraints are
checked, and the instantiation of any template used in the
specifier is done as if it were being done as part
of instantiating the declaration of the specialization at that point.

\pnum
\begin{note}
\ref{temp.point} defines the point of instantiation of a template specialization.
\end{note}

\pnum
There is an \impldef{maximum depth of recursive template instantiations} quantity
that specifies the limit on the total depth of recursive instantiations\iref{implimits},
which could involve more than one template.
The result of an infinite recursion in instantiation is undefined.
\begin{example}
\begin{codeblock}
template<class T> class X {
  X<T>* p;          // OK
  X<T*> a;          // implicit generation of \tcode{X<T>} requires
                    // the implicit instantiation of \tcode{X<T*>} which requires
                    // the implicit instantiation of \tcode{X<T**>} which \ldots
};
\end{codeblock}
\end{example}

\pnum
The \grammarterm{type-constraint}{s} and \grammarterm{requires-clause}
of a template specialization or member function
are not instantiated along with the specialization or function itself,
even for a member function of a local class;
substitution into the atomic constraints formed from them is instead performed
as specified in \ref{temp.constr.decl} and \ref{temp.constr.atomic}
when determining whether the constraints are satisfied
or as specified in \ref{temp.constr.decl} when comparing declarations.
\begin{note}
The satisfaction of constraints is determined during
template argument deduction\iref{temp.deduct} and
overload resolution\iref{over.match}.
\end{note}
\begin{example}
\begin{codeblock}
template<typename T> concept C = sizeof(T) > 2;
template<typename T> concept D = C<T> && sizeof(T) > 4;

template<typename T> struct S {
  S() requires C<T> { }         // \#1
  S() requires D<T> { }         // \#2
};

S<char> s1;                     // error: no matching constructor
S<char[8]> s2;                  // OK, calls \#2
\end{codeblock}
When \tcode{S<char>} is instantiated, both constructors are part of the
specialization. Their constraints are not satisfied, and
they suppress the implicit declaration of a default constructor for
\tcode{S<char>}\iref{class.default.ctor}, so there is no viable constructor
for \tcode{s1}.
\end{example}
\begin{example}
\begin{codeblock}
template<typename T> struct S1 {
  template<typename U>
    requires false
  struct Inner1;                // ill-formed, no diagnostic required
};

template<typename T> struct S2 {
  template<typename U>
    requires (sizeof(T[-(int)sizeof(T)]) > 1)
  struct Inner2;                // ill-formed, no diagnostic required
};
\end{codeblock}
The class \tcode{S1<T>::Inner1} is ill-formed, no diagnostic required, because
it has no valid specializations.
\tcode{S2} is ill-formed, no diagnostic required, since no substitution into
the constraints of its \tcode{Inner2} template would result in a valid
expression.
\end{example}

\rSec2[temp.explicit]{Explicit instantiation}

\pnum
\indextext{instantiation!explicit}%
\indextext{\idxcode{extern template}|see{instantiation, explicit}}%
A class, function, variable, or member template specialization can be explicitly
instantiated from its template.
A member function, member class or static data member of a class template can
be explicitly instantiated from the member definition associated with its class
template.

\pnum
The syntax for explicit instantiation is:

\begin{bnf}
\nontermdef{explicit-instantiation}\br
  \opt{\keyword{extern}} \keyword{template} declaration
\end{bnf}

There are two forms of explicit instantiation: an explicit instantiation
definition and an explicit instantiation declaration. An explicit instantiation
declaration begins with the \keyword{extern} keyword.

\pnum
An explicit instantiation shall not use
a \grammarterm{storage-class-specifier}\iref{dcl.stc}
other than \keyword{thread_local}.
An explicit instantiation of a
function template,
member function of a class template, or
variable template
shall not
use the \keyword{inline}, \keyword{constexpr}, or \keyword{consteval} specifiers.
No \grammarterm{attribute-specifier-seq}\iref{dcl.attr.grammar}
shall appertain to an explicit instantiation.

\pnum
If the explicit instantiation is for a class or member class, the
\grammarterm{elaborated-type-specifier} in the \grammarterm{declaration}
shall include a \grammarterm{simple-template-id};
otherwise, the \grammarterm{declaration}
shall be a \grammarterm{simple-declaration} whose \grammarterm{init-declarator-list}
comprises a single \grammarterm{init-declarator}
that does not have an \grammarterm{initializer}.
If the explicit instantiation is for a variable template specialization,
the \grammarterm{unqualified-id} in the \grammarterm{declarator}
shall be a \grammarterm{simple-template-id}.
\begin{example}
\begin{codeblock}
template<class T> class Array { void mf(); };
template class Array<char>;
template void Array<int>::mf();

template<class T> void sort(Array<T>& v) { @\commentellip@ }
template void sort(Array<char>&);       // argument is deduced here\iref{temp.arg.explicit}

namespace N {
  template<class T> void f(T&) { }
}
template void N::f<int>(int&);
\end{codeblock}
\end{example}

\pnum
An explicit instantiation does not introduce a name\iref{basic.scope.scope}.
A declaration of a function template, a variable template, a member function
or static data member
of a class template, or a member function template of a class or class
template shall be reachable from any explicit instantiation of that entity.
A definition
of a class template, a member class of a class template, or a member class
template of a class or class template shall be reachable from any explicit instantiation
of that entity unless an explicit
specialization of the entity with the same template arguments
is reachable therefrom.
If the \grammarterm{declaration}
of the explicit instantiation names an implicitly-declared special member
function\iref{special}, the program is ill-formed.

\pnum
The \grammarterm{declaration} in an \grammarterm{explicit-instantiation} and
the \grammarterm{declaration} produced by the corresponding substitution
into the templated function, variable, or class
are two declarations of the same entity.
\begin{note}
These declarations need to have matching types as specified in~\ref{basic.link}, except as specified in~\ref{except.spec}.
\begin{example}
\begin{codeblock}
template<typename T> T var = {};
template float var<float>;      // OK, instantiated variable has type \tcode{float}
template int var<int[16]>[];    // OK, absence of major array bound is permitted
template int *var<int>;         // error: instantiated variable has type \tcode{int}

template<typename T> auto av = T();
template int av<int>;           // OK, variable with type \tcode{auto} can be redeclared with type \keyword{int}

template<typename T> auto f() {}
template void f<int>();         // error: function with deduced return type
                                // redeclared with non-deduced return type\iref{dcl.spec.auto}
\end{codeblock}
\end{example}
\end{note}
Despite its syntactic form, the \grammarterm{declaration} in an \grammarterm{explicit-instantiation} for a variable is not itself a definition and does not conflict with the definition instantiated by an explicit instantiation definition for that variable.

\pnum
For a given set of template arguments, if an explicit
instantiation of a template appears after a declaration of
an explicit specialization for that template, the explicit
instantiation has no effect. Otherwise, for an explicit instantiation
definition, the definition of a
function template, a variable template, a member
function template, or a member function or static
data member of a class template shall be present in every
translation unit in which it is explicitly instantiated.

\pnum
\begin{note}
An explicit instantiation of a constrained template needs
to satisfy that template's associated constraints\iref{temp.constr.decl}.
The satisfaction of constraints is determined
% FIXME: What is a "template name"? Does this mean "simple-template-id"?
when forming the template name of an explicit instantiation
in which all template arguments are specified\iref{temp.names},
or, for explicit instantiations of function templates,
during template argument deduction\iref{temp.deduct.decl}
when one or more trailing template arguments are left unspecified.
\end{note}

\pnum
An explicit instantiation that names a class
template specialization is also an explicit
instantiation of the same kind (declaration or definition) of each
of its direct non-template members
that has not been previously explicitly specialized in
the translation unit containing the explicit instantiation,
provided that the associated constraints, if any,
of that member are satisfied by the template arguments of the explicit
instantiation\iref{temp.constr.decl,temp.constr.constr},
except as described below.
\begin{note}
In addition, it will typically be an explicit instantiation of certain
\indextext{implementation-dependent}%
implementation-dependent data about the class.
\end{note}

\pnum
An explicit instantiation definition that names a class template
specialization explicitly instantiates the class template specialization
and is an explicit instantiation definition of only those
members that have been defined at the point of instantiation.

\pnum
An explicit instantiation of a prospective destructor\iref{class.dtor}
shall correspond to the selected destructor of the class.

\pnum
If an entity is the subject of both an explicit instantiation declaration
and an explicit instantiation definition in the same translation unit, the
definition shall follow the declaration. An entity that is the subject of an
explicit instantiation declaration and that is also used
in a way that would otherwise cause an implicit instantiation\iref{temp.inst}
in the translation unit
shall be the subject of an explicit instantiation definition somewhere in the
program; otherwise the program is ill-formed, no diagnostic required.
\begin{note}
This rule does apply to inline functions even though an
explicit instantiation declaration of such an entity has no other normative
effect. This is needed to ensure that if the address of an inline function is
taken in a translation unit in which the implementation chose to suppress the
out-of-line body, another translation unit will supply the body.
\end{note}
An explicit instantiation declaration shall not name a specialization of a
template with internal linkage.

\pnum
An explicit instantiation does not constitute a use of a default argument,
so default argument instantiation is not done.
\begin{example}
\begin{codeblock}
char* p = 0;
template<class T> T g(T x = &p) { return x; }
template int g<int>(int);       // OK even though \tcode{\&p} isn't an \tcode{int}.
\end{codeblock}
\end{example}

\rSec2[temp.expl.spec]{Explicit specialization}

\pnum
\indextext{specialization!template explicit}%
An explicit specialization of any of the following:
\begin{itemize}
\item
function template
\item
class template
\item
variable template
\item
member function of a class template
\item
static data member of a class template
\item
member class of a class template
\item
member enumeration of a class template
\item
member class template of a class or class template
\item
member function template of a class or class template
\end{itemize}
can be declared by a declaration introduced by
\tcode{\keyword{template}<>};
that is:
\indextext{\idxgram{explicit-specialization}}%

\begin{bnf}
\nontermdef{explicit-specialization}\br
  \keyword{template} \terminal{<} \terminal{>} declaration
\end{bnf}

\begin{example}
\begin{codeblock}
template<class T> class stream;

template<> class stream<char> { @\commentellip@ };    // \#1

template<class T> class Array { @\commentellip@ };
template<class T> void sort(Array<T>& v) { @\commentellip@ }

template<> void sort<int>(Array<int>&);         // \#2
template<> void sort(Array<char*>&);            // \#3 template argument is deduced\iref{temp.arg.explicit}
\end{codeblock}

Given these declarations,
\#1 will be used as the definition of streams of
\tcode{char}s;
other streams will be handled by class template specializations instantiated
from the class template.
Similarly,
\#2 will be used as the sort function for arguments of
type \tcode{Array<int>} and
\#3 will be used for arguments
of type
\tcode{Array<char*>};
other
\tcode{Array}
types will be sorted by functions generated from the function template.
\end{example}

\pnum
The \grammarterm{declaration} in an \grammarterm{explicit-specialization}
shall not be an \grammarterm{export-declaration}.
An explicit specialization shall not use
a \grammarterm{storage-class-specifier}\iref{dcl.stc}
other than \keyword{thread_local}.

\pnum
An explicit specialization
may be declared in any scope in which the corresponding primary template
may be defined\iref{dcl.meaning,class.mem,temp.mem}.

\pnum
An explicit specialization does not introduce a name\iref{basic.scope.scope}.
A declaration of a function template, class template, or variable template being explicitly
specialized shall be reachable from the declaration of
the explicit specialization.
\begin{note}
A declaration, but not a definition of the template is needed.
\end{note}
The definition of a class or class template shall be reachable from the
declaration of an explicit specialization for a member template of the class
or class template.
\begin{example}
\begin{codeblock}
template<> class X<int> { @\commentellip@ };          // error: \tcode{X} not a template

template<class T> class X;

template<> class X<char*> { @\commentellip@ };        // OK, \tcode{X} is a template
\end{codeblock}
\end{example}

\pnum
A member function, a member function template, a member class,
a member enumeration, a
member class template,
a static data member, or a static data member template of a class template
may be explicitly specialized for a class specialization that is implicitly
instantiated;
in this case, the definition of the class template shall
be reachable from the explicit specialization for the member of the class
template.
If such an explicit specialization for the member of a class template names an
implicitly-declared special member function\iref{special},
the program is ill-formed.

\pnum
A member of an explicitly specialized class is not implicitly
instantiated from the member declaration of the class template;
instead, the member of the class template specialization shall itself be
explicitly defined if its definition is required.
The definition of the class template explicit specialization
shall be reachable from the definition of any member of it.
The definition of an explicitly specialized class is unrelated to the
definition of a generated specialization.
That is, its members need
not have the same names, types, etc.\ as the members of a generated
specialization.
Members of an explicitly specialized
class template are defined in the same manner as members of normal classes, and
not using the \tcode{\keyword{template}<>} syntax.
The same is true when defining a member of an explicitly specialized member
class. However, \tcode{\keyword{template}<>} is used in defining a member of an explicitly
specialized member class template that is specialized as a class template.
\begin{example}
\begin{codeblock}
template<class T> struct A {
  struct B { };
  template<class U> struct C { };
};

template<> struct A<int> {
  void f(int);
};

void h() {
  A<int> a;
  a.f(16);          // \tcode{A<int>::f} must be defined somewhere
}

// \tcode{\keyword{template}<>} not used for a member of an explicitly specialized class template
void A<int>::f(int) { @\commentellip@ }

template<> struct A<char>::B {
  void f();
};
// \tcode{\keyword{template}<>} also not used when defining a member of an explicitly specialized member class
void A<char>::B::f() { @\commentellip@ }

template<> template<class U> struct A<char>::C {
  void f();
};
// \tcode{\keyword{template}<>} is used when defining a member of an explicitly specialized member class template
// specialized as a class template
template<>
template<class U> void A<char>::C<U>::f() { @\commentellip@ }

template<> struct A<short>::B {
  void f();
};
template<> void A<short>::B::f() { @\commentellip@ }              // error: \tcode{\keyword{template}<>} not permitted

template<> template<class U> struct A<short>::C {
  void f();
};
template<class U> void A<short>::C<U>::f() { @\commentellip@ }    // error: \tcode{\keyword{template}<>} required
\end{codeblock}
\end{example}

\pnum
If a template, a member template or a member of a class template is explicitly
specialized, a declaration of that specialization shall be reachable from
every use of
that specialization that would cause an implicit instantiation to take place,
in every translation unit in which such a use occurs;
no diagnostic is required.
If the program does not provide a definition for an explicit specialization and
either the specialization is used in a way that would cause an implicit
instantiation to take place or the member is a virtual member function,
the program is ill-formed, no diagnostic required.
An implicit instantiation is never generated for an explicit specialization
that is declared but not defined.
\begin{example}
\begin{codeblock}
class String { };
template<class T> class Array { @\commentellip@ };
template<class T> void sort(Array<T>& v) { @\commentellip@ }

void f(Array<String>& v) {
  sort(v);          // use primary template \tcode{sort(Array<T>\&)}, \tcode{T} is \tcode{String}
}

template<> void sort<String>(Array<String>& v);     // error: specialization after use of primary template
template<> void sort<>(Array<char*>& v);            // OK, \tcode{sort<char*>} not yet used
template<class T> struct A {
  enum E : T;
  enum class S : T;
};
template<> enum A<int>::E : int { eint };           // OK
template<> enum class A<int>::S : int { sint };     // OK
template<class T> enum A<T>::E : T { eT };
template<class T> enum class A<T>::S : T { sT };
template<> enum A<char>::E : char { echar };        // error: \tcode{A<char>::E} was instantiated
                                                    // when \tcode{A<char>} was instantiated
template<> enum class A<char>::S : char { schar };  // OK
\end{codeblock}
\end{example}

\pnum
The placement of explicit specialization declarations for function templates, class
templates, variable templates,
member functions of class templates, static data members of class
templates, member classes of class templates, member enumerations of class
templates, member class templates of class
templates, member function templates of class templates,
static data member templates of class templates,
member functions of
member templates of class templates, member functions of member templates of
non-template classes,
static data member templates of non-template classes,
member function templates of member classes of class
templates, etc., and the placement of partial specialization declarations
of class templates, variable templates,
member class templates of non-template classes,
static data member templates of non-template classes, member
class templates of class templates, etc., can affect whether a program is
well-formed according to the relative positioning of the explicit specialization
declarations and their points of instantiation in the translation unit as
specified above and below.
When writing a specialization, be careful about its location;
or to make it compile will be such a trial as to kindle its self-immolation.

\pnum
\begin{note}
A class template explicit specialization that has been declared but
not defined can be used exactly like other
incompletely-defined classes\iref{basic.types}.
\begin{example}
\begin{codeblock}
template<class T> class X;                      // \tcode{X} is a class template
template<> class X<int>;

X<int>* p;                                      // OK, pointer to declared class \tcode{X<int>}
X<int> x;                                       // error: object of incomplete class \tcode{X<int>}
\end{codeblock}
\end{example}
\end{note}

\pnum
\begin{note}
An explicit specialization of a constrained template needs
to satisfy that template's associated constraints\iref{temp.constr.decl}.
The satisfaction of constraints is determined
when forming the template name of an explicit specialization
in which all template arguments are specified\iref{temp.names},
or, for explicit specializations of function templates,
during template argument deduction\iref{temp.deduct.decl}
when one or more trailing template arguments are left unspecified.
\end{note}

\pnum
A function with the same name as a template and a type that exactly matches that
of a template specialization is not an explicit specialization\iref{temp.fct}.

\pnum
Whether an explicit specialization of a function or variable template
is inline, constexpr, constinit, or consteval
is determined by the explicit specialization and
is independent of those properties of the template.
Similarly,
attributes and \grammarterm{function-contract-specifier}s
appearing in the declaration of a template
have no effect on an explicit specialization of that template.
\begin{example}
\begin{codeblock}
template<class T> void f(T) { @\commentellip@ }
template<class T> inline T g(T) { @\commentellip@ }

template<> inline void f<>(int) { @\commentellip@ }   // OK, inline
template<> int g<>(int) { @\commentellip@ }           // OK, not inline

template<typename> [[noreturn]] void h([[maybe_unused]] int i);
template<> void h<int>(int i) {
    // Implementations are expected not to warn that the function returns
    // but can warn about the unused parameter.
}
\end{codeblock}
\end{example}

\pnum
An explicit specialization of a static data member of a template
or an explicit specialization of a static data member template is a
definition if the declaration includes an initializer;
otherwise, it is a declaration.
\begin{note}
The definition of a static data member of a template
for which default-initialization is desired
can use functional cast notation\iref{expr.type.conv}:

\begin{codeblock}
template<> X Q<int>::x;                         // declaration
template<> X Q<int>::x ();                      // error: declares a function
template<> X Q<int>::x = X();                   // definition
\end{codeblock}
\end{note}

\pnum
A member or a member template of a class template may be explicitly specialized
for a given implicit instantiation of the class template, even if the member
or member template is defined in the class template definition.
An explicit specialization of a member or member template is specified using the
syntax for explicit specialization.
\begin{example}
\begin{codeblock}
template<class T> struct A {
  void f(T);
  template<class X1> void g1(T, X1);
  template<class X2> void g2(T, X2);
  void h(T) { }
};

// specialization
template<> void A<int>::f(int);

// out of class member template definition
template<class T> template<class X1> void A<T>::g1(T, X1) { }

// member template specialization
template<> template<class X1> void A<int>::g1(int, X1);

// member template specialization
template<> template<>
  void A<int>::g1(int, char);           // \tcode{X1} deduced as \tcode{char}
template<> template<>
  void A<int>::g2<char>(int, char);     // \tcode{X2} specified as \tcode{char}

// member specialization even if defined in class definition
template<> void A<int>::h(int) { }
\end{codeblock}
\end{example}

\pnum
A member or a member template may be nested within many enclosing class
templates.
In an explicit specialization for such a member,
the member declaration shall be preceded by a
\tcode{\keyword{template}<>}
for each enclosing class template that is explicitly specialized.
\begin{example}
\begin{codeblock}
template<class T1> class A {
  template<class T2> class B {
    void mf();
  };
};
template<> template<> class A<int>::B<double>;
template<> template<> void A<char>::B<char>::mf();
\end{codeblock}
\end{example}

\pnum
In an explicit specialization declaration for a member of a class template or
a member template that appears in namespace scope,
the member template and some of its enclosing class templates may remain
unspecialized,
except that the declaration shall not explicitly specialize a class member
template if its enclosing class templates are not explicitly specialized
as well.
In such an explicit specialization declaration, the keyword
\keyword{template}
followed by a
\grammarterm{template-parameter-list}
shall be provided instead of the
\tcode{\keyword{template}<>}
preceding the explicit specialization declaration of the member.
The types of the
\grammarterm{template-parameter}{s}
in the
\grammarterm{template-parameter-list}
shall be the same as those specified in the primary template definition.
\begin{example}
\begin{codeblock}
template <class T1> class A {
  template<class T2> class B {
    template<class T3> void mf1(T3);
    void mf2();
  };
};
template <> template <class X>
  class A<int>::B {
      template <class T> void mf1(T);
  };
template <> template <> template<class T>
  void A<int>::B<double>::mf1(T t) { }
template <class Y> template <>
  void A<Y>::B<double>::mf2() { }       // error: \tcode{B<double>} is specialized but
                                        // its enclosing class template \tcode{A} is not
\end{codeblock}
\end{example}

\pnum
A specialization of a member function template, member class template,
or static data member template of
a non-specialized class template is itself a template.

\pnum
An explicit specialization declaration shall not be a friend declaration.

\pnum
Default function arguments shall not be specified in a declaration or
a definition for one of the following explicit specializations:
\begin{itemize}
\item
the explicit specialization of a function template;
\item
the explicit specialization of a member function template;
\item
the explicit specialization of a member function of a class template where
the class template specialization to which the member function specialization
belongs is implicitly instantiated.
\begin{note}
Default function arguments can be specified in the declaration or
definition of a member function of a class template specialization that is
explicitly specialized.
\end{note}
\end{itemize}

\rSec1[temp.fct.spec]{Function template specializations}

\rSec2[temp.fct.spec.general]{General}

\pnum
\indextext{template!function}%
A function instantiated from a function template is called a function template
specialization; so is an explicit specialization of a function template.
Template arguments can be explicitly specified when naming the function
template specialization, deduced from the context (e.g.,
deduced from the function arguments in a call to the function template
specialization, see~\ref{temp.deduct}), or obtained from default template arguments.

\pnum
Each function template specialization instantiated from a template
has its own copy of any static variable.
\begin{example}
\begin{codeblock}
template<class T> void f(T* p) {
  static T s;
};

void g(int a, char* b) {
  f(&a);            // calls \tcode{f<int>(int*)}
  f(&b);            // calls \tcode{f<char*>(char**)}
}
\end{codeblock}

Here
\tcode{f<int>(int*)}
has a static variable
\tcode{s}
of type
\tcode{int}
and
\tcode{f<char*>(char**)}
has a static variable
\tcode{s}
of type
\tcode{char*}.
\end{example}

\rSec2[temp.arg.explicit]{Explicit template argument specification}

\pnum
\indextext{specification!template argument}%
Template arguments can be specified when referring to a function
template specialization that is not a specialization of a constructor template
by qualifying the function template
name with the list of
\grammarterm{template-argument}{s}
in the same way as
\grammarterm{template-argument}{s}
are specified in uses of a class template specialization.
\begin{example}
\begin{codeblock}
template<class T> void sort(Array<T>& v);
void f(Array<dcomplex>& cv, Array<int>& ci) {
  sort<dcomplex>(cv);                   // \tcode{sort(Array<dcomplex>\&)}
  sort<int>(ci);                        // \tcode{sort(Array<int>\&)}
}
\end{codeblock}
and
\begin{codeblock}
template<class U, class V> U convert(V v);

void g(double d) {
  int i = convert<int,double>(d);       // \tcode{int convert(double)}
  char c = convert<char,double>(d);     // \tcode{char convert(double)}
}
\end{codeblock}
\end{example}

\pnum
Template arguments shall not be specified
when referring to a specialization of
a constructor template\iref{class.ctor,class.qual}.

\pnum
A template argument list may be specified when referring to a specialization
of a function template
\begin{itemize}
\item
when a function is called,
\item
when the address of a function is taken, when a function initializes a
reference to function, or when a pointer to member function is formed,
\item
in an explicit specialization,
\item
in an explicit instantiation, or
\item
in a friend declaration.
\end{itemize}

\pnum
Trailing template arguments that can be deduced\iref{temp.deduct} or
obtained from default \grammarterm{template-argument}{s}
may be omitted from the list of explicit \grammarterm{template-argument}{s}.
\begin{note}
A trailing template parameter pack\iref{temp.variadic} not otherwise deduced will be
deduced as an empty sequence of template arguments.
\end{note}
If all of the template arguments can be
deduced or obtained from default \grammarterm{template-argument}{s},
they may all be omitted;
in this case, the empty template argument list \tcode{<>}
itself may also be omitted.
\begin{example}
\begin{codeblock}
template<class X, class Y> X f(Y);
template<class X, class Y, class ... Z> X g(Y);
void h() {
  int i = f<int>(5.6);          // \tcode{Y} deduced as \tcode{double}
  int j = f(5.6);               // error: \tcode{X} cannot be deduced
  f<void>(f<int, bool>);        // \tcode{Y} for outer \tcode{f} deduced as \tcode{int (*)(bool)}
  f<void>(f<int>);              // error: \tcode{f<int>} does not denote a single function template specialization
  int k = g<int>(5.6);          // \tcode{Y} deduced as \tcode{double}; \tcode{Z} deduced as an empty sequence
  f<void>(g<int, bool>);        // \tcode{Y} for outer \tcode{f} deduced as \tcode{int (*)(bool)},
                                // \tcode{Z} deduced as an empty sequence
}
\end{codeblock}
\end{example}

\pnum
\begin{note}
An empty template argument list can be used to indicate that a given
use refers to a specialization of a function template even when a
non-template function\iref{dcl.fct} is visible that would otherwise be used.
For example:

\begin{codeblock}
template <class T> int f(T);    // \#1
int f(int);                     // \#2
int k = f(1);                   // uses \#2
int l = f<>(1);                 // uses \#1
\end{codeblock}
\end{note}

\pnum
Template arguments that are present shall be specified in the declaration
order of their corresponding template parameters.
The template argument list shall not specify more
\grammarterm{template-argument}{s}
than there are corresponding
\grammarterm{template-parameter}{s}
unless one of the \grammarterm{template-parameter}{s} declares a template
parameter pack.
\begin{example}
\begin{codeblock}
template<class X, class Y, class Z> X f(Y,Z);
template<class ... Args> void f2();
void g() {
  f<int,const char*,double>("aa",3.0);
  f<int,const char*>("aa",3.0); // \tcode{Z} deduced as \tcode{double}
  f<int>("aa",3.0);             // \tcode{Y} deduced as \tcode{const char*}; \tcode{Z} deduced as \tcode{double}
  f("aa",3.0);                  // error: \tcode{X} cannot be deduced
  f2<char, short, int, long>(); // OK
}
\end{codeblock}
\end{example}

\pnum
Implicit conversions\iref{conv} will be performed on a function argument
to convert it to the type of the corresponding function parameter if
the parameter type contains no template parameters
that participate in template argument deduction.
\begin{note}
Template parameters do not participate in template argument deduction if
they are explicitly specified.
For example,

\begin{codeblock}
template<class T> void f(T);

class Complex {
  Complex(double);
};

void g() {
  f<Complex>(1);    // OK, means \tcode{f<Complex>(Complex(1))}
}
\end{codeblock}
\end{note}

\pnum
\begin{note}
Because the explicit template argument list follows the function
template name, and because
constructor templates\iref{class.ctor} are named without using a
function name\iref{class.qual}, there is no way to provide an explicit
template argument list for these function templates.
\end{note}

\pnum
Template argument deduction can extend the sequence of template
arguments corresponding to a template parameter pack, even when the
sequence contains explicitly specified template arguments.
\begin{example}
\begin{codeblock}
template<class ... Types> void f(Types ... values);

void g() {
  f<int*, float*>(0, 0, 0);     // \tcode{Types} deduced as the sequence \tcode{int*}, \tcode{float*}, \tcode{int}
}
\end{codeblock}
\end{example}

\rSec2[temp.deduct]{Template argument deduction}

\rSec3[temp.deduct.general]{General}

\pnum
When a
function template
specialization is referenced, all of the
template arguments shall have values.
The values can be
explicitly specified or, in some cases, be deduced from the use
or obtained from default
\grammarterm{template-argument}{s}.
\begin{example}
\begin{codeblock}
void f(Array<dcomplex>& cv, Array<int>& ci) {
  sort(cv);                     // calls \tcode{sort(Array<dcomplex>\&)}
  sort(ci);                     // calls \tcode{sort(Array<int>\&)}
}
\end{codeblock}
and
\begin{codeblock}
void g(double d) {
  int i = convert<int>(d);      // calls \tcode{convert<int,double>(double)}
  int c = convert<char>(d);     // calls \tcode{convert<char,double>(double)}
}
\end{codeblock}
\end{example}

\pnum
When an explicit template argument list is specified, if the
given \grammarterm{template-id} or
\grammarterm{splice-specialization-specifier} is not valid\iref{temp.names},
type deduction fails.
Otherwise, the specified template argument values are substituted for the
corresponding template parameters as specified below.

\pnum
After this substitution is performed, the function parameter type
adjustments described in~\ref{dcl.fct} are performed.
\begin{example}
A parameter type of ``\tcode{void (const int, int[5])}'' becomes
``\tcode{void(*)(int,int*)}''.
\end{example}
\begin{note}
A top-level qualifier in a function parameter declaration does not affect
the function type but still affects the type of the function parameter
variable within the function.
\end{note}
\begin{example}
\begin{codeblock}
template <class T> void f(T t);
template <class X> void g(const X x);
template <class Z> void h(Z, Z*);

int main() {
  // \#1: function type is \tcode{f(int)}, \tcode{t} is non \keyword{const}
  f<int>(1);

  // \#2: function type is \tcode{f(int)}, \tcode{t} is \keyword{const}
  f<const int>(1);

  // \#3: function type is \tcode{g(int)}, \tcode{x} is \keyword{const}
  g<int>(1);

  // \#4: function type is \tcode{g(int)}, \tcode{x} is \keyword{const}
  g<const int>(1);

  // \#5: function type is \tcode{h(int, const int*)}
  h<const int>(1,0);
}
\end{codeblock}
\end{example}

\pnum
\begin{note}
\tcode{f<int>(1)} and \tcode{f<const int>(1)} call distinct functions
even though both of the functions called have the same function type.
\end{note}

\pnum
The resulting substituted and adjusted function type is used as
the type of the function template for template argument
deduction.  If a template argument has not been deduced and its
corresponding template parameter has a default argument, the
template argument is determined by substituting the template
arguments determined for preceding template parameters into the
default argument. If the substitution results in an invalid type,
as described above, type deduction fails.
\begin{example}
\begin{codeblock}
template <class T, class U = double>
void f(T t = 0, U u = 0);

void g() {
  f(1, 'c');        // \tcode{f<int,char>(1,'c')}
  f(1);             // \tcode{f<int,double>(1,0)}
  f();              // error: \tcode{T} cannot be deduced
  f<int>();         // \tcode{f<int,double>(0,0)}
  f<int,char>();    // \tcode{f<int,char>(0,0)}
}
\end{codeblock}
\end{example}

When all template arguments have been deduced or obtained from
default template arguments, all uses of template parameters in
the template parameter list of the template
are replaced with the corresponding deduced
or default argument values. If the substitution results in an
invalid type, as described above, type deduction fails.
If the function template has associated constraints\iref{temp.constr.decl},
those constraints are checked for satisfaction\iref{temp.constr.constr}.
If the constraints are not satisfied, type deduction fails.
In the context of a function call, if type deduction has not yet failed, then
for those function parameters for which the function call has arguments,
each function parameter with a type that was non-dependent
before substitution of any explicitly-specified template arguments
is checked against its corresponding argument;
if the corresponding argument cannot be implicitly converted
to the parameter type, type deduction fails.
\begin{note}
Overload resolution will check the other parameters, including
parameters with dependent types in which
no template parameters participate in template argument deduction and
parameters that became non-dependent due to substitution of
explicitly-specified template arguments.
\end{note}
If type deduction has not yet failed, then
all uses of template parameters in the function type are
replaced with the corresponding deduced or default argument values.
If the substitution results in an invalid type, as described above,
type deduction fails.
\begin{example}
\begin{codeblock}
template <class T> struct Z {
  typedef typename T::x xx;
};
template <class T> concept C = requires { typename T::A; };
template <C T> typename Z<T>::xx f(void *, T);          // \#1
template <class T> void f(int, T);                      // \#2
struct A {} a;
struct ZZ {
  template <class T, class = typename Z<T>::xx> operator T *();
  operator int();
};
int main() {
  ZZ zz;
  f(1, a);              // OK, deduction fails for \#1 because there is no conversion from \tcode{int} to \tcode{\keyword{void}*}
  f(zz, 42);            // OK, deduction fails for \#1 because \tcode{C<int>} is not satisfied
}
\end{codeblock}
\end{example}

\pnum
At certain points in the template argument deduction process it is necessary
to take a function type that makes use of template parameters and replace those
template parameters with the corresponding template arguments. This is done at
the beginning of template argument deduction when any explicitly specified
template arguments are substituted into the function type, and again at the end
of template argument deduction when any template arguments that were deduced or
obtained from default arguments are substituted.

\pnum
\indextext{deduction!deduction substitution loci}%
The \defn{deduction substitution loci} are
\begin{itemize}
\item the function type outside of the \grammarterm{noexcept-specifier},
\item the \grammarterm{explicit-specifier},
\item the template parameter declarations, and
\item the template argument list of a partial specialization\iref{temp.spec.partial.general}.
\end{itemize}
The substitution occurs in all types and expressions that are used
in the deduction substitution loci.
The expressions include not only
constant expressions such as those that appear in array bounds or as constant
template arguments but also general expressions (i.e., non-constant expressions)
inside \tcode{sizeof}, \keyword{decltype}, and other contexts that allow non-constant
expressions. The substitution proceeds in lexical order and stops when
a condition that causes deduction to fail is encountered.
If substitution into different declarations of the same function template would
cause template instantiations to occur in a different order or not at all,
the program is ill-formed; no diagnostic required.
\begin{note}
The equivalent substitution in
exception specifications\iref{except.spec}
and function contract assertions\iref{dcl.contract.func}
is done only when
the \grammarterm{noexcept-specifier}
or \grammarterm{function-contract-specifier}, respectively,
is instantiated,
at which point a program is ill-formed
if the substitution results in an invalid type or expression.
\end{note}
\begin{example}
\begin{codeblock}
template <class T> struct A { using X = typename T::X; };
template <class T> typename T::X f(typename A<T>::X);
template <class T> void f(...) { }
template <class T> auto g(typename A<T>::X) -> typename T::X;
template <class T> void g(...) { }
template <class T> typename T::X h(typename A<T>::X);
template <class T> auto h(typename A<T>::X) -> typename T::X;   // redeclaration
template <class T> void h(...) { }

void x() {
  f<int>(0);        // OK, substituting return type causes deduction to fail
  g<int>(0);        // error, substituting parameter type instantiates \tcode{A<int>}
  h<int>(0);        // ill-formed, no diagnostic required
}
\end{codeblock}
\end{example}

\pnum
If a substitution results in an invalid type or expression, type deduction fails. An
invalid type or expression is one that would be ill-formed, with a diagnostic
required, if written in the same context using the substituted arguments.
\begin{note}
If no diagnostic is required, the program is still ill-formed.
Access checking is done as part of the substitution process.
\end{note}
Invalid types and expressions can result in a deduction failure
only in the immediate context of the deduction substitution loci.
\begin{note}
The substitution into types and expressions can result
in effects such as the instantiation of class template specializations and/or
function template specializations, the generation of implicitly-defined functions,
etc. Such effects are not in the ``immediate context'' and can result in the
program being ill-formed.
\end{note}

\pnum
When substituting into a \grammarterm{lambda-expression},
substitution into its body is not in the immediate context.
\begin{note}
The intent is to avoid requiring implementations to deal with
substitution failure involving arbitrary statements.
\begin{example}
\begin{codeblock}
template <class T>
  auto f(T) -> decltype([]() { T::invalid; } ());
void f(...);
f(0);               // error: invalid expression not part of the immediate context

template <class T, std::size_t = sizeof([]() { T::invalid; })>
  void g(T);
void g(...);
g(0);               // error: invalid expression not part of the immediate context

template <class T>
  auto h(T) -> decltype([x = T::invalid]() { });
void h(...);
h(0);               // OK, calls \tcode{h(...)}

template <class T>
  auto i(T) -> decltype([]() -> typename T::invalid { });
void i(...);
i(0);               // OK, calls \tcode{i(...)}

template <class T>
  auto j(T t) -> decltype([](auto x) -> decltype(x.invalid) { } (t));
void j(...);
j(0);               // OK, calls \tcode{j(...)}
\end{codeblock}
\end{example}
\end{note}

\pnum
\begin{example}
\begin{codeblock}
struct X { };
struct Y {
  Y(X) {}
};

template <class T> auto f(T t1, T t2) -> decltype(t1 + t2);     // \#1
X f(Y, Y);                                                      // \#2

X x1, x2;
X x3 = f(x1, x2);   // deduction fails on \#1 (cannot add \tcode{X+X}), calls \#2
\end{codeblock}
\end{example}

\pnum
\begin{note}
Type deduction can fail for the following reasons:
\begin{itemize}
\item Attempting to instantiate a pack expansion containing multiple packs of differing lengths.
\item
Attempting to create an array with an element type that is \keyword{void}, a
function type, or a reference type, or attempting
to create an array with a size that is zero or negative.
\begin{example}
\begin{codeblock}
template <class T> int f(T[5]);
int I = f<int>(0);
int j = f<void>(0);             // invalid array
\end{codeblock}
\end{example}
\item
Attempting to use a type that is not a class or enumeration type in a qualified name.
\begin{example}
\begin{codeblock}
template <class T> int f(typename T::B*);
int i = f<int>(0);
\end{codeblock}
\end{example}
\item
Attempting to use a type in a \grammarterm{nested-name-specifier} of a
\grammarterm{qualified-id} when
that type does not contain the specified member, or
\begin{itemize}
\item
the specified member is not a type where a type is required, or
\item
the specified member is not a template where a template is required, or
\item
the specified member is not a non-type, non-template where a non-type,
non-template is required.
\end{itemize}
\begin{example}
\begin{codeblock}
template <int I> struct X { };
template <template <class T> class> struct Z { };
template <class T> void f(typename T::Y*) {}
template <class T> void g(X<T::N>*) {}
template <class T> void h(Z<T::TT>*) {}
struct A {};
struct B { int Y; };
struct C {
  typedef int N;
};
struct D {
  typedef int TT;
};

int main() {
  // Deduction fails in each of these cases:
  f<A>(0);          // \tcode{A} does not contain a member \tcode{Y}
  f<B>(0);          // The \tcode{Y} member of \tcode{B} is not a type
  g<C>(0);          // The \tcode{N} member of \tcode{C} is not a non-type, non-template name
  h<D>(0);          // The \tcode{TT} member of \tcode{D} is not a template
}
\end{codeblock}
\end{example}
\item
Attempting to create a pointer to reference type.
\item
Attempting to create a reference to \keyword{void}.
\item
Attempting to create ``pointer to member of \tcode{T}'' when \tcode{T} is not a
class type.
\begin{example}
\begin{codeblock}
template <class T> int f(int T::*);
int i = f<int>(0);
\end{codeblock}
\end{example}
\item
Attempting to give an invalid type to a constant template parameter.
\begin{example}
\begin{codeblock}
template <class T, T> struct S {};
template <class T> int f(S<T, T{}>*);   // \#1
class X {
  int m;
};
int i0 = f<X>(0);   // \#1 uses a value of non-structural type \tcode{X} as a constant template argument
\end{codeblock}
\end{example}

\item
Attempting to perform an invalid conversion in either a template
argument expression, or an expression used in the function
declaration.
\begin{example}
\begin{codeblock}
template <class T, T*> int f(int);
int i2 = f<int,1>(0);           // can't convert \tcode{1} to \tcode{int*}
\end{codeblock}
\end{example}

\item
Attempting to create a function type in which a parameter has a type
of \keyword{void}, or in which the return type is a function type
or array type.

\item
%FIXME: What's it mean to "give" a type "to" a parameter?
%FIXME: See also "Attempting to give an invalid type to ..." above.
Attempting to give to
an explicit object parameter of a lambda's function call operator
a type not permitted for such\iref{expr.prim.lambda.closure}.
\end{itemize}
\end{note}

\pnum
\begin{example}
In the following example,
assuming a \tcode{signed char}
cannot represent the value 1000,
a narrowing conversion\iref{dcl.init.list}
would be required
to convert the \grammarterm{template-argument}
of type \tcode{int} to \tcode{signed char},
therefore substitution fails for the
second template\iref{temp.arg.nontype}.

\begin{codeblock}
template <int> int f(int);
template <signed char> int f(int);
int i1 = f<1000>(0);            // OK
int i2 = f<1>(0);               // ambiguous; not narrowing
\end{codeblock}
\end{example}

\rSec3[temp.deduct.call]{Deducing template arguments from a function call}

\pnum
Template argument deduction is done by comparing each function
template parameter type (call it
\tcode{P})
that contains template parameters that participate in template argument deduction
with the type of the corresponding argument of the call (call it
\tcode{A})
as described below.
If removing references and cv-qualifiers from \tcode{P} gives
$\tcode{std::initializer_list<P}^{\prime}\tcode{>}$
or $\tcode{P}'\tcode{[N]}$
for some $\tcode{P}'$ and \tcode{N} and the
argument is a non-empty initializer list\iref{dcl.init.list}, then deduction is
performed instead for each element of the initializer list independently,
taking $\tcode{P}'$
as separate function template parameter types $\tcode{P}'_i$
and the $i^\text{th}$ initializer element as the corresponding argument.
In the $\tcode{P}'\tcode{[N]}$ case, if \tcode{N} is a constant template parameter,
\tcode{N} is deduced from the length of the initializer list.
Otherwise, an initializer list argument causes the
parameter to be considered a non-deduced context\iref{temp.deduct.type}.
\begin{example}
\begin{codeblock}
template<class T> void f(std::initializer_list<T>);
f({1,2,3});                     // \tcode{T} deduced as \tcode{int}
f({1,"asdf"});                  // error: \tcode{T} deduced as both \tcode{int} and \tcode{const char*}

template<class T> void g(T);
g({1,2,3});                     // error: no argument deduced for \tcode{T}

template<class T, int N> void h(T const(&)[N]);
h({1,2,3});                     // \tcode{T} deduced as \tcode{int}; \tcode{N} deduced as \tcode{3}

template<class T> void j(T const(&)[3]);
j({42});                        // \tcode{T} deduced as \tcode{int}; array bound not considered

struct Aggr { int i; int j; };
template<int N> void k(Aggr const(&)[N]);
k({1,2,3});                     // error: deduction fails, no conversion from \tcode{int} to \tcode{Aggr}
k({{1},{2},{3}});               // OK, \tcode{N} deduced as \tcode{3}

template<int M, int N> void m(int const(&)[M][N]);
m({{1,2},{3,4}});               // \tcode{M} and \tcode{N} both deduced as \tcode{2}

template<class T, int N> void n(T const(&)[N], T);
n({{1},{2},{3}},Aggr());        // OK, \tcode{T} is \tcode{Aggr}, \tcode{N} is \tcode{3}

template<typename T, int N> void o(T (* const (&)[N])(T)) { }
int f1(int);
int f4(int);
char f4(char);
o({ &f1, &f4 });                                // OK, \tcode{T} deduced as \tcode{int} from first element, nothing
                                                // deduced from second element, \tcode{N} deduced as \tcode{2}
o({ &f1, static_cast<char(*)(char)>(&f4) });    // error: conflicting deductions for \tcode{T}
\end{codeblock}
\end{example}
For a function parameter pack that occurs at the end
of the \grammarterm{parameter-declaration-list},
deduction is performed for each remaining argument of the call,
taking the type \tcode{P}
of the \grammarterm{declarator-id} of the function parameter pack
as the corresponding function template parameter type.
Each deduction deduces template arguments for subsequent positions in
the template parameter packs expanded by the function parameter pack.
When a function parameter pack appears in a non-deduced
context\iref{temp.deduct.type}, the type of that pack is
never deduced.
\begin{example}
\begin{codeblock}
template<class ... Types> void f(Types& ...);
template<class T1, class ... Types> void g(T1, Types ...);
template<class T1, class ... Types> void g1(Types ..., T1);

void h(int x, float& y) {
  const int z = x;
  f(x, y, z);                   // \tcode{Types} deduced as \tcode{int}, \tcode{float}, \tcode{const int}
  g(x, y, z);                   // \tcode{T1} deduced as \tcode{int}; \tcode{Types} deduced as \tcode{float}, \tcode{int}
  g1(x, y, z);                  // error: \tcode{Types} is not deduced
  g1<int, int, int>(x, y, z);   // OK, no deduction occurs
}
\end{codeblock}
\end{example}

\pnum
If
\tcode{P}
is not a reference type:

\begin{itemize}
\item
If
\tcode{A}
is an array type, the pointer type produced by the array-to-pointer
standard conversion\iref{conv.array} is used in place of
\tcode{A}
for type deduction;
otherwise,
\item
If
\tcode{A}
is a function type, the pointer type produced by the
function-to-pointer standard conversion\iref{conv.func} is used in place
of
\tcode{A}
for type
deduction; otherwise,
\item
If
\tcode{A}
is a cv-qualified type, the top-level cv-qualifiers of
\tcode{A}'s
type are ignored for type deduction.
\end{itemize}

\pnum
\indextext{reference!forwarding}%
If
\tcode{P}
is a cv-qualified type, the top-level cv-qualifiers of
\tcode{P}'s
type are ignored for type deduction.
If
\tcode{P}
is a reference type, the type
referred to by
\tcode{P}
is used for type deduction.
\begin{example}
\begin{codeblock}
template<class T> int f(const T&);
int n1 = f(5);                  // calls \tcode{f<int>(const int\&)}
const int i = 0;
int n2 = f(i);                  // calls \tcode{f<int>(const int\&)}
template <class T> int g(volatile T&);
int n3 = g(i);                  // calls \tcode{g<const int>(const volatile int\&)}
\end{codeblock}
\end{example}
A \defn{forwarding reference}
is an rvalue reference to a cv-unqualified template parameter
that does not represent a template parameter of a class template
(during class template argument deduction\iref{over.match.class.deduct}).
If \tcode{P} is a forwarding reference and the argument is an
lvalue, the type ``lvalue reference to \tcode{A}'' is used in place of \tcode{A} for type
deduction.
\begin{example}
\begin{codeblock}
template <class T> int f(T&& heisenreference);
template <class T> int g(const T&&);
int i;
int n1 = f(i);                  // calls \tcode{f<int\&>(int\&)}
int n2 = f(0);                  // calls \tcode{f<int>(int\&\&)}
int n3 = g(i);                  // error: would call \tcode{g<int>(const int\&\&)}, which
                                // would bind an rvalue reference to an lvalue

template <class T> struct A {
  template <class U>
    A(T&&, U&&, int*);          // \#1: \tcode{T\&\&} is not a forwarding reference.
                                // \tcode{U\&\&} is a forwarding reference.
  A(T&&, int*);                 // \#2
};

template <class T> A(T&&, int*) -> A<T>;    // \#3: \tcode{T\&\&} is a forwarding reference.

int *ip;
A a{i, 0, ip};                  // error: cannot deduce from \#1
A a0{0, 0, ip};                 // uses \#1 to deduce \tcode{A<int>} and \#1 to initialize
A a2{i, ip};                    // uses \#3 to deduce \tcode{A<int\&>} and \#2 to initialize
\end{codeblock}
\end{example}

\pnum
In general, the deduction process attempts to find template argument
values that will make the deduced
\tcode{A}
identical to
\tcode{A}
(after
the type
\tcode{A}
is transformed as described above).
However, there are
three cases that allow a difference:

\begin{itemize}
\item
If the original
\tcode{P}
is a reference type, the deduced
\tcode{A}
(i.e.,
the type referred to by the reference) can be more cv-qualified than
the transformed \tcode{A}.
\item
The transformed \tcode{A}
can be another pointer or pointer-to-member type that can be converted
to the deduced
\tcode{A}
via a function pointer conversion\iref{conv.fctptr} and/or
qualification conversion\iref{conv.qual}.

\item
If
\tcode{P}
is a class and
\tcode{P}
has the form
\grammarterm{simple-template-id} or
\opt{\keyword{typename}} \grammarterm{splice-specialization-specifier},
then
the transformed \tcode{A}
can be a derived class \tcode{D} of the
deduced
\tcode{A}.
Likewise, if
\tcode{P}
is a pointer to a class of the form
\grammarterm{simple-template-id} or
\opt{\keyword{typename}} \grammarterm{splice-specialization-specifier},
the transformed \tcode{A}
can be a pointer to a
derived class \tcode{D} of the class pointed to by the deduced
\tcode{A}.
However, if there is a class \tcode{C} that is
a (direct or indirect) base class of \tcode{D} and
derived (directly or indirectly) from a class \tcode{B} and
that would be a valid deduced \tcode{A},
the deduced \tcode{A} cannot be \tcode{B} or pointer to \tcode{B},
respectively.
\begin{example}
\begin{codeblock}
template <typename... T> struct X;
template <> struct X<> {};
template <typename T, typename... Ts>
  struct X<T, Ts...> : X<Ts...> {};
struct D : X<int> {};
struct E : X<>, X<int> {};

template <typename... T>
int f(const X<T...>&);
int x = f(D());     // calls \tcode{f<int>}, not \tcode{f<>}
                    // \tcode{B} is \tcode{X<>}, \tcode{C} is \tcode{X<int>}
int z = f(E());     // calls \tcode{f<int>}, not \tcode{f<>}
\end{codeblock}
\end{example}
\end{itemize}

\pnum
These alternatives are considered only if type deduction would
otherwise fail.
If they yield more than one possible deduced
\tcode{A},
the type deduction fails.
\begin{note}
If a template parameter
is not used in any of the function parameters of a function template,
or is used only in a non-deduced context, its corresponding
\grammarterm{template-argument}
cannot be deduced from a function call and the
\grammarterm{template-argument}
must be explicitly specified.
\end{note}

\pnum
When
\tcode{P}
is a function type, function pointer type, or pointer-to-member-function type:
\begin{itemize}
\item
If the argument is an overload set containing one or more function templates,
the parameter is treated as a non-deduced context.
\item
If the argument is an overload set (not containing function templates), trial
argument deduction is attempted using each of the members of the set
whose associated constraints\iref{temp.constr.constr} are satisfied.
If all successful deductions yield the same deduced \tcode{A},
that deduced \tcode{A} is the result of deduction;
otherwise, the parameter is treated as a non-deduced context.
\end{itemize}

\pnum
\begin{example}
\begin{codeblock}
// Only one function of an overload set matches the call so the function parameter is a deduced context.
template <class T> int f(T (*p)(T));
int g(int);
int g(char);
int i = f(g);       // calls \tcode{f(int (*)(int))}
\end{codeblock}
\end{example}

\pnum
\begin{example}
\begin{codeblock}
// Ambiguous deduction causes the second function parameter to be a non-deduced context.
template <class T> int f(T, T (*p)(T));
int g(int);
char g(char);
int i = f(1, g);    // calls \tcode{f(int, int (*)(int))}
\end{codeblock}
\end{example}

\pnum
\begin{example}
\begin{codeblock}
// The overload set contains a template, causing the second function parameter to be a non-deduced context.
template <class T> int f(T, T (*p)(T));
char g(char);
template <class T> T g(T);
int i = f(1, g);    // calls \tcode{f(int, int (*)(int))}
\end{codeblock}
\end{example}

\pnum
\begin{example}
\begin{codeblock}
// All arguments for placeholder type deduction\iref{dcl.type.auto.deduct} yield the same deduced type.
template<bool B> struct X {
  static void f(short) requires B;  // \#1
  static void f(short);             // \#2
};
void test() {
  auto x = &X<true>::f;     // OK, deduces \tcode{void(*)(short)}, selects \#1
  auto y = &X<false>::f;    // OK, deduces \tcode{void(*)(short)}, selects \#2
}
\end{codeblock}
\end{example}

\rSec3[temp.deduct.funcaddr]{Deducing template arguments taking the address of a function template}

\pnum
Template arguments can be deduced from the type specified when taking
the address of an overload set\iref{over.over}.
If there is a target,
the function template's function type and the target type
are used as the types of
\tcode{P}
and
\tcode{A},
and the deduction is done as
described in~\ref{temp.deduct.type}.
Otherwise, deduction is performed with empty sets of types \tcode{P} and \tcode{A}.

\pnum
A placeholder type\iref{dcl.spec.auto} in the return type of a
function template is a non-deduced context. If template argument
deduction succeeds for such a function, the return type is determined
from instantiation of the function body.

\rSec3[temp.deduct.conv]{Deducing conversion function template arguments}

\pnum
Template argument deduction is done by comparing the return type of
the
conversion function template
(call it
\tcode{P})
with the type specified by the \grammarterm{conversion-type-id} of the
\grammarterm{conversion-function-id} being looked up
(call it \tcode{A}) as described in~\ref{temp.deduct.type}.
If the \grammarterm{conversion-function-id} is constructed during
overload resolution\iref{over.match.funcs},
the rules in the remainder of this subclause apply.

\pnum
If \tcode{P} is a reference type, the type referred to by \tcode{P} is used in place
of \tcode{P} for type deduction and for any further references to or transformations of
\tcode{P} in the remainder of this subclause.

\pnum
If
\tcode{A}
is not a reference type:

\begin{itemize}
\item
If
\tcode{P}
is an array type, the pointer type produced by the
array-to-pointer standard conversion\iref{conv.array} is used in place of
\tcode{P}
for type
deduction; otherwise,
\item
If
\tcode{P}
is a function type, the pointer type produced by the
function-to-pointer standard conversion\iref{conv.func} is used in place of
\tcode{P}
for
type deduction; otherwise,
\item
If
\tcode{P}
is a cv-qualified type, the top-level cv-qualifiers of
\tcode{P}'s
type are ignored for type deduction.
\end{itemize}

\pnum
If
\tcode{A}
is a cv-qualified type, the top-level cv-qualifiers of
\tcode{A}'s
type are ignored for type deduction.
If
\tcode{A}
is a
reference type, the type referred to by
\tcode{A}
is used for type deduction.

\pnum
In general, the deduction process attempts to find template argument
values that will make the deduced
\tcode{A}
identical to
\tcode{A}.
However, certain attributes of \tcode{A} may be ignored:

\begin{itemize}
\item
If the original \tcode{A} is a reference type,
any cv-qualifiers of \tcode{A}
(i.e., the type referred to by the reference).
\item
If the original \tcode{A} is
a function pointer or pointer-to-member-function type
with a potentially-throwing exception specification\iref{except.spec},
the exception specification.
\item
Any cv-qualifiers in \tcode{A}
that can be restored by a qualification conversion.
\end{itemize}
These attributes are ignored only if type deduction would
otherwise fail.
If ignoring them allows more than one possible deduced
\tcode{A},
the type deduction fails.

\rSec3[temp.deduct.partial]{Deducing template arguments during partial ordering}

\pnum
Template argument deduction is done by comparing certain types associated with
the two function templates being compared.

\pnum
Two sets of types are used to determine the partial ordering.  For each of
the templates involved there is the original function type and the
transformed function type.
\begin{note}
The creation of the transformed type is described in~\ref{temp.func.order}.
\end{note}
The deduction process uses the
transformed type as the argument template and the original type of the
other template as the parameter template.  This process is done twice
for each type involved in the partial ordering comparison: once using
the transformed template-1 as the argument template and template-2 as
the parameter template and again using the transformed template-2 as
the argument template and template-1 as the parameter template.

\pnum
The types used to determine the ordering depend on the context in which
the partial ordering is done:

\begin{itemize}
\item
In the context of a function call, the types used are those function parameter types
for which the function call has arguments.
\begin{footnote}
Default arguments
are not considered to be arguments in this context; they only become arguments
after a function has been selected.
\end{footnote}
\item
In the context of a call to a conversion function, the return types of
the conversion function templates are used.
\item
In other contexts\iref{temp.func.order} the function template's function
type is used.
\end{itemize}

\pnum
Each type nominated above from the parameter template and the corresponding type from the
argument template are used as the types of
\tcode{P}
and
\tcode{A}.

\pnum
Before the partial ordering is done, certain transformations are performed
on the types used for partial ordering:

\begin{itemize}
\item
If
\tcode{P}
is a reference type,
\tcode{P}
is replaced by the type referred to.
\item
If
\tcode{A}
is a reference type,
\tcode{A}
is replaced by the type referred to.
\end{itemize}

\pnum
If both
\tcode{P}
and
\tcode{A}
were reference types (before being replaced with the type referred to
above), determine which of the two types (if any) is more cv-qualified
than the other; otherwise the types are considered to be equally
cv-qualified for partial ordering purposes. The result of this
determination will be used below.

\pnum
Remove any top-level cv-qualifiers:
\begin{itemize}
\item
If
\tcode{P}
is a cv-qualified type,
\tcode{P}
is replaced by the cv-unqualified version of
\tcode{P}.
\item
If
\tcode{A}
is a cv-qualified type,
\tcode{A}
is replaced by the cv-unqualified version of
\tcode{A}.
\end{itemize}

\pnum
Using the resulting types
\tcode{P}
and
\tcode{A},
the deduction is then done as described in~\ref{temp.deduct.type}.
If \tcode{P} is a function parameter pack, the type \tcode{A} of each remaining
parameter type of the argument template is compared with the type \tcode{P} of
the \grammarterm{declarator-id} of the function parameter pack. Each comparison
deduces template arguments for subsequent positions in the template parameter
packs expanded by the function parameter pack.
Similarly, if \tcode{A} was transformed from a function parameter pack,
it is compared with each remaining parameter type of the parameter template.
If deduction succeeds for a given type,
the type from the argument template is considered to be at least as specialized
as the type from the parameter template.
\begin{example}
\begin{codeblock}
template<class... Args>           void f(Args... args);         // \#1
template<class T1, class... Args> void f(T1 a1, Args... args);  // \#2
template<class T1, class T2>      void f(T1 a1, T2 a2);         // \#3

f();                // calls \#1
f(1, 2, 3);         // calls \#2
f(1, 2);            // calls \#3; non-variadic template \#3 is more specialized
                    // than the variadic templates \#1 and \#2
\end{codeblock}
\end{example}

\pnum
If, for a given type, the
types are identical after the transformations above
and both \tcode{P} and \tcode{A} were reference types (before being replaced with the
type referred to above):
\begin{itemize}
\item if the type from the argument template was an lvalue reference and the type
from the parameter template was not,
the parameter type is not considered to be
at least as specialized as the argument type; otherwise,
\item if the type from
the argument template is more cv-qualified than the type from the
parameter template (as described above),
the parameter type is not considered to be
at least as specialized as the argument type.
\end{itemize}

\pnum
\indextext{at least as specialized as|see{more specialized}}%
Function template \tcode{F}
is \defnx{at least as specialized as}{more specialized}
function template \tcode{G} if,
for each pair of types used to determine the ordering,
the type from \tcode{F}
is at least as specialized as
the type from \tcode{G}.
\tcode{F}
is \defnx{more specialized than}{more specialized!function template}
\tcode{G} if
\tcode{F}
is at least as specialized as
\tcode{G} and
\tcode{G}
is not at least as specialized as
\tcode{F}.

\pnum
If, after considering the above, function template \tcode{F}
is at least as specialized as function template \tcode{G} and vice-versa, and
if \tcode{G} has a trailing function parameter pack
for which \tcode{F} does not have a corresponding parameter, and
if \tcode{F} does not have a trailing function parameter pack,
then \tcode{F} is more specialized than \tcode{G}.

\pnum
In most cases,
deduction fails if not all template parameters have values,
but for partial ordering purposes a template
parameter may remain without a value provided it is not used in the
types being used for partial ordering.
\begin{note}
A template parameter used in a non-deduced context is considered used.
\end{note}
\begin{example}
\begin{codeblock}
template <class T> T f(int);            // \#1
template <class T, class U> T f(U);     // \#2
void g() {
  f<int>(1);                            // calls \#1
}
\end{codeblock}
\end{example}

\pnum
\begin{note}
Partial ordering of function templates containing
template parameter packs is independent of the number of deduced arguments
for those template parameter packs.
\end{note}
\begin{example}
\begin{codeblock}
template<class ...> struct Tuple { };
template<class ... Types> void g(Tuple<Types ...>);                 // \#1
template<class T1, class ... Types> void g(Tuple<T1, Types ...>);   // \#2
template<class T1, class ... Types> void g(Tuple<T1, Types& ...>);  // \#3

g(Tuple<>());                   // calls \#1
g(Tuple<int, float>());         // calls \#2
g(Tuple<int, float&>());        // calls \#3
g(Tuple<int>());                // calls \#3
\end{codeblock}
\end{example}

\rSec3[temp.deduct.type]{Deducing template arguments from a type}

\pnum
Template arguments can be deduced in several different contexts, but
in each case a type that is specified in terms of template parameters
(call it
\tcode{P})
is compared with an actual type (call it
\tcode{A}),
and an attempt is made to find template argument values (a type for a type
parameter, a value for a constant template parameter, or a template for a
template template parameter) that will make
\tcode{P},
after substitution of the deduced values (call it the deduced
\tcode{A}),
compatible with
\tcode{A}.

\pnum
In some cases, the deduction is done using a single set of types
\tcode{P}
and
\tcode{A},
in other cases, there will be a set of corresponding types
\tcode{P}
and
\tcode{A}.
Type deduction is done
independently for each
\tcode{P/A}
pair, and the deduced template
argument values are then combined.
If type deduction cannot be done
for any
\tcode{P/A}
pair, or if for any pair the deduction leads to more than
one possible set of deduced values, or if different pairs yield
different deduced values, or if any template argument remains neither
deduced nor explicitly specified, template argument deduction fails.
The type of a type parameter
is only deduced from an array bound
if it is not otherwise deduced.

\pnum
A given type
\tcode{P}
can be composed from a number of other
types, templates, and constant template argument values:

\begin{itemize}
\item
A function type includes the types of each of the function parameters,
the return type, and its exception specification.
\item
A pointer-to-member type includes the type of the class object pointed to
and the type of the member pointed to.
\item
A type that is a specialization of a class template (e.g.,
\tcode{A<int>})
includes the types, templates, and constant template argument values referenced by the
template argument list of the specialization.
\item
An array type includes the array element type and the value of the
array bound.
\end{itemize}

\pnum
In most cases, the types, templates, and constant template argument values that are used
to compose
\tcode{P}
participate in template argument deduction.
That is,
they may be used to determine the value of a template argument, and
template argument deduction fails if
the value so determined is not consistent with the values determined
elsewhere.
In certain contexts, however, the value does not
participate in type deduction, but instead uses the values of template
arguments that were either deduced elsewhere or explicitly specified.
If a template parameter is used only in non-deduced contexts and is not
explicitly specified, template argument deduction fails.
\begin{note}
Under \ref{temp.deduct.call},
if \tcode{P} contains no template parameters that appear
in deduced contexts, no deduction is done, so \tcode{P} and \tcode{A}
need not have the same form.
\end{note}

\pnum
The non-deduced contexts are:

\indextext{context!non-deduced}%
\begin{itemize}
\item
The
\grammarterm{nested-name-specifier}
of a type that was specified using a
\grammarterm{qualified-id}.
\item
A \grammarterm{pack-index-specifier} or a \grammarterm{pack-index-expression}.
\item
A \grammarterm{type-constraint}.
\item
The \grammarterm{expression} of a \grammarterm{decltype-specifier}.
\item
The \grammarterm{constant-expression} of a \grammarterm{splice-specifier}.
\item
A constant template argument or an array bound in which a subexpression
references a template parameter.
\item
A template parameter used in the parameter type of a function parameter that
has a default argument that is being used in the call for which argument
deduction is being done.
\item
A function parameter for which the associated argument is an
overload set such that one or more of the following apply:
\begin{itemize}
\item
functions whose associated constraints are satisfied and
that do not all have the same function type
match the function parameter type (resulting in an ambiguous deduction), or
\item
no function whose associated constraints are satisfied
matches the function parameter type, or
\item
the overload set supplied as an argument contains one or more function templates.
\end{itemize}
\begin{tailnote}
A particular function from the overload set is selected\iref{over.over}
after template argument deduction has succeeded\iref{temp.over}.
\end{tailnote}
\item A function parameter for which the associated argument is an initializer
list\iref{dcl.init.list} but the parameter does not have
a type for which deduction from an initializer list is specified\iref{temp.deduct.call}.
\begin{example}
\begin{codeblock}
template<class T> void g(T);
g({1,2,3});                 // error: no argument deduced for \tcode{T}
\end{codeblock}
\end{example}
\item A function parameter pack that does not occur at the end of the
\grammarterm{parameter-declaration-list}.
\end{itemize}

\pnum
When a type name is specified in a way that includes a non-deduced
context, all of the types that comprise that type name are also
non-deduced.
However, a compound type can include both deduced and non-deduced types.
\begin{example}
If a type is specified as
\tcode{A<T>::B<T2>},
both
\tcode{T}
and
\tcode{T2}
are non-deduced.
Likewise, if a type is specified as
\tcode{A<I+J>::X<T>},
\tcode{I},
\tcode{J},
and
\tcode{T}
are non-deduced.
If a type is specified as
\keyword{void}
\tcode{f(typename}
\tcode{A<T>::B,}
\tcode{A<T>)},
the
\tcode{T}
in
\tcode{A<T>::B}
is non-deduced but
the
\tcode{T}
in
\tcode{A<T>}
is deduced.
\end{example}

\pnum
\begin{example}
Here is an example in which different parameter/argument pairs produce
inconsistent template argument deductions:

\begin{codeblock}
template<class T> void f(T x, T y) { @\commentellip@ }
struct A { @\commentellip@ };
struct B : A { @\commentellip@ };
void g(A a, B b) {
  f(a,b);           // error: \tcode{T} deduced as both \tcode{A} and \tcode{B}
  f(b,a);           // error: \tcode{T} deduced as both \tcode{A} and \tcode{B}
  f(a,a);           // OK, \tcode{T} is \tcode{A}
  f(b,b);           // OK, \tcode{T} is \tcode{B}
}
\end{codeblock}

Here is an example where two template arguments are deduced from a
single function parameter/argument pair.
This can lead to conflicts
that cause type deduction to fail:

\begin{codeblock}
template <class T, class U> void f(T (*)(T, U, U));

int g1(int, float, float);
char g2(int, float, float);
int g3(int, char, float);

void r() {
  f(g1);            // OK, \tcode{T} is \tcode{int} and \tcode{U} is \tcode{float}
  f(g2);            // error: \tcode{T} deduced as both \tcode{char} and \tcode{int}
  f(g3);            // error: \tcode{U} deduced as both \tcode{char} and \tcode{float}
}
\end{codeblock}

Here is an example where the exception specification of a function type
is deduced:

\begin{codeblock}
template<bool E> void f1(void (*)() noexcept(E));
template<bool> struct A { };
template<bool B> void f2(void (*)(A<B>) noexcept(B));

void g1();
void g2() noexcept;
void g3(A<true>);

void h() {
  f1(g1);           // OK, \tcode{E} is \tcode{false}
  f1(g2);           // OK, \tcode{E} is \tcode{true}
  f2(g3);           // error: \tcode{B} deduced as both \tcode{true} and \tcode{false}
}
\end{codeblock}

Here is an example where a qualification conversion applies between the
argument type on the function call and the deduced template argument type:

\begin{codeblock}
template<class T> void f(const T*) { }
int* p;
void s() {
  f(p);             // \tcode{f(const int*)}
}
\end{codeblock}

Here is an example where the template argument is used to instantiate
a derived class type of the corresponding function parameter type:

\begin{codeblock}
template <class T> struct B { };
template <class T> struct D : public B<T> {};
struct D2 : public B<int> {};
template <class T> void f(B<T>&) {}
void t() {
  D<int> d;
  D2     d2;
  f(d);             // calls \tcode{f(B<int>\&)}
  f(d2);            // calls \tcode{f(B<int>\&)}
}
\end{codeblock}
\end{example}

\pnum
A type template argument \tcode{T},
a constant template argument \tcode{i},
a template template argument \tcode{TT}
denoting a class template or an alias template, or
a template template argument \tcode{VV}
denoting a variable template or a concept
can be deduced if
\tcode{P}
and
\tcode{A}
have one of the following forms:
\begin{codeblock}
@\opt{\cv{}}@ T
T*
T&
T&&
@\opt{T}@[@\opt{i}@]
@\opt{T}@(@\opt{T}@) noexcept(@\opt{i}@)
@\opt{T}@ @\opt{T}@::*
@\opt{TT}@<T>
@\opt{TT}@<i>
@\opt{TT}@<TT>
@\opt{TT}@<VV>
@\opt{TT}@<>
\end{codeblock}
where
\begin{itemize}
\item
\tcode{\opt{T}} represents a type or parameter-type-list that either
satisfies these rules recursively,
is a non-deduced context in \tcode{P} or \tcode{A}, or
is the same non-dependent type in \tcode{P} and \tcode{A},

\item
\tcode{\opt{i}} represents an expression that either
is an \tcode{i},
is value-dependent in \tcode{P} or \tcode{A}, or
has the same constant value in \tcode{P} and \tcode{A},

\item
\tcode{\opt{TT}} represents either a class template or
a template template parameter, and

\item
\tcode{\keyword{noexcept}(\opt{i})} represents an
exception specification\iref{except.spec}
in which the (possibly-implicit, see~\ref{dcl.fct})
\grammarterm{noexcept-specifier}'s operand
satisfies the rules for an \tcode{\opt{i}} above.
\end{itemize}

\begin{note}
If a type matches such a form but contains no
\tcode{T}s, \tcode{i}s, or \tcode{TT}s, deduction is not possible.
\end{note}

Similarly,
\tcode{<$X$>} represents template argument lists where
at least one argument contains an $X$, where
$X$ is one of \tcode{T}, \tcode{i}, \tcode{TT}, or \tcode{VV};
and
\tcode{<>}
represents template argument lists where no argument contains a
\tcode{T}, an \tcode{i}, a \tcode{TT}, or a \tcode{VV}.

\pnum
If \tcode{P} has a form that contains
\tcode{<T>}, \tcode{<i>}, \tcode{<TT>}, or \tcode{<VV>},
then each argument $\mathtt{P}_i$ of the
respective template argument list of \tcode{P} is compared with the
corresponding argument $\mathtt{A}_i$ of the corresponding
template argument list of \tcode{A}. If the template argument list
of \tcode{P} contains a pack expansion that is not the last
template argument, the entire template argument list is a non-deduced
context. If $\texttt{P}_i$ is a pack expansion, then the pattern
of $\texttt{P}_i$ is compared with each remaining argument in the
template argument list of \tcode{A}. Each comparison deduces
template arguments for subsequent positions in the template parameter
packs expanded by $\texttt{P}_i$.
During partial ordering\iref{temp.deduct.partial}, if $\texttt{A}_i$ was
originally a pack expansion:
\begin{itemize}
\item if \tcode{P} does not contain a template argument corresponding to
$\texttt{A}_i$ then $\texttt{A}_i$ is ignored;

\item otherwise, if $\texttt{P}_i$ is not a pack expansion, template argument
deduction fails.
\end{itemize}
\begin{example}
\begin{codeblock}
template<class T1, class... Z> class S;                                 // \#1
template<class T1, class... Z> class S<T1, const Z&...> { };            // \#2
template<class T1, class T2>   class S<T1, const T2&> { };              // \#3
S<int, const int&> s;           // both \#2 and \#3 match; \#3 is more specialized

template<class T, class... U>            struct A { };                  // \#1
template<class T1, class T2, class... U> struct A<T1, T2*, U...> { };   // \#2
template<class T1, class T2>             struct A<T1, T2> { };          // \#3
template struct A<int, int*>;   // selects \#2
\end{codeblock}
\end{example}

\pnum
Similarly, if \tcode{P} has a form that contains
\tcode{(T)}, then each parameter type $\texttt{P}_i$
of the respective parameter-type-list\iref{dcl.fct} of
\tcode{P} is compared with the corresponding parameter type
$\texttt{A}_i$ of the corresponding parameter-type-list
of \tcode{A}.
If \tcode{P} and \tcode{A} are function types that originated from deduction when
taking the address of a function template\iref{temp.deduct.funcaddr} or when
deducing template arguments from a function declaration\iref{temp.deduct.decl}
and $\texttt{P}_i$ and $\texttt{A}_i$ are parameters of the top-level
parameter-type-list of \tcode{P} and \tcode{A}, respectively,
$\texttt{P}_i$ is adjusted if it is a forwarding reference\iref{temp.deduct.call}
and $\texttt{A}_i$ is an lvalue reference, in which case the type of
$\texttt{P}_i$ is changed to be the template parameter type (i.e., \tcode{T\&\&} is
changed to simply \tcode{T}).
\begin{note}
As a result, when $\texttt{P}_i$ is \tcode{T\&\&}
and $\texttt{A}_i$ is \tcode{X\&}, the adjusted $\texttt{P}_i$ will be \tcode{T},
causing \tcode{T} to be deduced as \tcode{X\&}.
\end{note}
\begin{example}
\begin{codeblock}
template <class T> void f(T&&);
template <> void f(int&) { }    // \#1
template <> void f(int&&) { }   // \#2
void g(int i) {
  f(i);                         // calls \tcode{f<int\&>(int\&)}, i.e., \#1
  f(0);                         // calls \tcode{f<int>(int\&\&)}, i.e., \#2
}
\end{codeblock}
\end{example}

If the \grammarterm{parameter-declaration}
corresponding to $\texttt{P}_i$ is a function parameter pack,
then the type of its \grammarterm{declarator-id} is compared with
each remaining parameter type in the parameter-type-list
of \tcode{A}. Each comparison deduces template arguments for
subsequent positions in the template parameter packs expanded by the
function parameter pack.
During partial ordering\iref{temp.deduct.partial}, if $\texttt{A}_i$ was
originally a function parameter pack:
\begin{itemize}
\item if \tcode{P} does not contain a function parameter type corresponding to
$\texttt{A}_i$ then $\texttt{A}_i$ is ignored;

\item otherwise, if $\texttt{P}_i$ is not a function parameter pack, template
argument deduction fails.
\end{itemize}
\begin{example}
\begin{codeblock}
template<class T, class... U> void f(T*, U...) { }  // \#1
template<class T>             void f(T) { }         // \#2
template void f(int*);                              // selects \#1
\end{codeblock}
\end{example}

\pnum
These forms can be used in the same way as
\tcode{T}
is for further composition of types.
\begin{example}
\begin{codeblock}
X<int> (*)(char[6])
\end{codeblock}
is of the form
\begin{codeblock}
@\grammarterm{template-name}@<T> (*)(@\placeholder{type}@[i])
\end{codeblock}
which is a variant of
\begin{codeblock}
@\placeholder{type}@ (*)(T)
\end{codeblock}
where type is
\tcode{X<int>}
and
\tcode{T}
is
\tcode{char[6]}.
\end{example}

\pnum
Template arguments cannot be deduced from function arguments involving
constructs other than the ones specified above.

\pnum
When the value of the argument
corresponding to a constant template parameter \tcode{P}
that is declared with a dependent type
is deduced from an expression,
the template parameters in the type of \tcode{P}
are deduced from the type of the value.
\begin{example}
\begin{codeblock}
template<long n> struct A { };

template<typename T> struct C;
template<typename T, T n> struct C<A<n>> {
  using Q = T;
};

using R = long;
using R = C<A<2>>::Q;           // OK; \tcode{T} was deduced as \tcode{long} from the
                                // template argument value in the type \tcode{A<2>}
\end{codeblock}
\end{example}

\pnum
The type of \tcode{N} in the type \tcode{T[N]} is \tcode{std::size_t}.
\begin{example}
\begin{codeblock}
template<typename T> struct S;
template<typename T, T n> struct S<int[n]> {
  using Q = T;
};

using V = decltype(sizeof 0);
using V = S<int[42]>::Q;        // OK; \tcode{T} was deduced as \tcode{std::size_t} from the type \tcode{int[42]}
\end{codeblock}
\end{example}

\pnum
The type of \tcode{B} in the \grammarterm{noexcept-specifier}
\tcode{\keyword{noexcept}(B)} of a function type is \tcode{bool}.
\begin{example}
\begin{codeblock}
template<bool> struct A { };
template<auto> struct B;
template<auto X, void (*F)() noexcept(X)> struct B<F> {
  A<X> ax;
};
void f_nothrow() noexcept;
B<f_nothrow> bn;                // OK, type of \tcode{X} deduced as \tcode{bool}
\end{codeblock}
\end{example}

\pnum
\begin{example}
\begin{codeblock}
template<class T, T i> void f(int (&a)[i]);
int v[10];
void g() {
  f(v);                         // OK, \tcode{T} is \tcode{std::size_t}
}
\end{codeblock}
\end{example}

\pnum
\begin{note}
Except for reference and pointer types, a major array bound is not part of a
function parameter type and cannot be deduced from an argument:
\begin{codeblock}
template<int i> void f1(int a[10][i]);
template<int i> void f2(int a[i][20]);
template<int i> void f3(int (&a)[i][20]);

void g() {
  int v[10][20];
  f1(v);                        // OK, \tcode{i} deduced as \tcode{20}
  f1<20>(v);                    // OK
  f2(v);                        // error: cannot deduce template-argument \tcode{i}
  f2<10>(v);                    // OK
  f3(v);                        // OK, \tcode{i} deduced as \tcode{10}
}
\end{codeblock}
\end{note}

\pnum
\begin{note}
If, in the declaration of a function template with a constant
template parameter, the constant template parameter
is used in a subexpression in the function parameter list,
the expression is a non-deduced context as specified above.
\begin{example}
\begin{codeblock}
template <int i> class A { @\commentellip@ };
template <int i> void g(A<i+1>);
template <int i> void f(A<i>, A<i+1>);
void k() {
  A<1> a1;
  A<2> a2;
  g(a1);                        // error: deduction fails for expression \tcode{i+1}
  g<0>(a1);                     // OK
  f(a1, a2);                    // OK
}
\end{codeblock}
\end{example}
\end{note}

\pnum
\begin{note}
Template parameters do not participate in template argument deduction if
they are used only in non-deduced contexts.
For example,

\begin{codeblock}
template<int i, typename T>
T deduce(typename A<T>::X x,    // \tcode{T} is not deduced here
         T t,                   // but \tcode{T} is deduced here
         typename B<i>::Y y);   // \tcode{i} is not deduced here
A<int> a;
B<77>  b;

int    x = deduce<77>(a.xm, 62, b.ym);
// \tcode{T} deduced as \tcode{int}; \tcode{a.xm} must be convertible to \tcode{A<int>::X}
// \tcode{i} is explicitly specified to be \tcode{77}; \tcode{b.ym} must be convertible to \tcode{B<77>::Y}
\end{codeblock}
\end{note}

\pnum
If \tcode{P} has a form that contains \tcode{<i>},
deduction fails unless the type of \tcode{i} is the same as that
of the corresponding template parameter
\tcode{p} in the specialization (from \tcode{A})
of the template named by the enclosing \grammarterm{simple-template-id} or
\grammarterm{splice-specialization-specifier};
if the declared type of \tcode{i} contains a placeholder type,
the corresponding template argument for the purposes of
placeholder type deduction\iref{dcl.type.auto.deduct}
is an \grammarterm{id-expression} for \tcode{p}.
If \tcode{P} has a form that contains \tcode{[i]}, and if the type of
\tcode{i} is not an integral type, deduction fails.
\begin{footnote}
Although the
\grammarterm{template-argument}
corresponding to a template parameter of type
\tcode{bool}
can be deduced from an array bound, the resulting value will always be
\tcode{true}
because the array bound will be nonzero.
\end{footnote}
If \tcode{P} has a form that includes \tcode{\keyword{noexcept}(i)} and
the type of \tcode{i} is not \tcode{bool}, deduction fails.
\begin{example}
\begin{codeblock}
template<int i> class A { @\commentellip@ };
template<short s> void f(A<s>);
void k1() {
  A<1> a;
  f(a);                 // error: deduction fails for conversion from \tcode{int} to \tcode{short}
  f<1>(a);              // OK
}

template<const short cs> class B { };
template<short s> void g(B<s>);
void k2() {
  B<1> b;
  g(b);                 // OK, cv-qualifiers are ignored on template parameter types
}

template<auto> struct C;
template<long long x> void f(C<x> *);
void g(C<0LL> *ap) {
  f(ap);                // OK, deduces \tcode{long long} value from \tcode{0LL}
}

template<int> struct D;
template<auto x> void f(D<x> *);
void g(D<0LL> *ap) {
  f(ap);                // OK, deduces \tcode{x} as an \tcode{int} value
}

template<int &> struct E;
template<auto x> void f(E<x> *);
int v;
void g(E<v> *bp) {
  f(bp);                // error: type \tcode{int} of \tcode{x} does not match the \tcode{int \&} type
}                       // of the template parameter in the \tcode{E<v>} specialization of \tcode{E}

template<const int &> struct F;
template<decltype(auto) x> void f(F<x> *);
int i;
void g(F<i> *ap) {
  f(ap);                // OK, deduces \tcode{x} as a constant template parameter of type \tcode{const int \&}
}

template <decltype(auto) q> struct G;
template <auto x> long *f(G<x> *);              // \#1
template <decltype(auto) x> short *f(G<x> *);   // \#2

const int j = 0;
short *g(G<(j)> *ap) {  // OK, \tcode{q} has type \tcode{const int \&}
  return f(ap);         // OK, only \#2 matches
}

long *g(G<j> *ap) {     // OK, \tcode{q} has type \tcode{int}
  return f(ap);         // OK, \#1 is more specialized
}
\end{codeblock}
\end{example}

\pnum
A
\grammarterm{template-argument}
can be deduced from a function, pointer to function, or
pointer-to-member-function type.

\begin{example}
\begin{codeblock}
template<class T> void f(void(*)(T,int));
template<class T> void foo(T,int);
void g(int,int);
void g(char,int);

void h(int,int,int);
void h(char,int);
int m() {
  f(&g);            // error: ambiguous
  f(&h);            // OK, void \tcode{h(char,int)} is a unique match
  f(&foo);          // error: type deduction fails because \tcode{foo} is a template
}
\end{codeblock}
\end{example}

\pnum
A template
\grammarterm{type-parameter}
cannot be deduced from the type of a function default argument.
\begin{example}
\begin{codeblock}
template <class T> void f(T = 5, T = 7);
void g() {
  f(1);             // OK, calls \tcode{f<int>(1,7)}
  f();              // error: cannot deduce \tcode{T}
  f<int>();         // OK, calls \tcode{f<int>(5,7)}
}
\end{codeblock}
\end{example}

\pnum
The
\grammarterm{template-argument}
corresponding to a template template parameter
is deduced from the type of the
\grammarterm{template-argument}
of a class template specialization used in the argument list of a function call.
\begin{example}
\begin{codeblock}
template <template <class T> class X> struct A { };
template <template <class T> class X> void f(A<X>) { }
template<class T> struct B { };
A<B> ab;
f(ab);              // calls \tcode{f(A<B>)}
\end{codeblock}
\end{example}

\pnum
\begin{note}
Template argument deduction involving parameter
packs\iref{temp.variadic} can deduce zero or more arguments for
each parameter pack.
\end{note}
\begin{example}
\begin{codeblock}
template<class> struct X { };
template<class R, class ... ArgTypes> struct X<R(int, ArgTypes ...)> { };
template<class ... Types> struct Y { };
template<class T, class ... Types> struct Y<T, Types& ...> { };

template<class ... Types> int f(void (*)(Types ...));
void g(int, float);

X<int> x1;                      // uses primary template
X<int(int, float, double)> x2;  // uses partial specialization; \tcode{ArgTypes} contains \tcode{float}, \tcode{double}
X<int(float, int)> x3;          // uses primary template
Y<> y1;                         // uses primary template; \tcode{Types} is empty
Y<int&, float&, double&> y2;    // uses partial specialization; \tcode{T} is \tcode{int\&}, \tcode{Types} contains \tcode{float}, \tcode{double}
Y<int, float, double> y3;       // uses primary template; \tcode{Types} contains \tcode{int}, \tcode{float}, \tcode{double}
int fv = f(g);                  // OK; \tcode{Types} contains \tcode{int}, \tcode{float}
\end{codeblock}
\end{example}

\rSec3[temp.deduct.decl]{Deducing template arguments from a function declaration}

\pnum
In a declaration whose \grammarterm{declarator-id} refers to a specialization
of a function template, template argument deduction is performed to identify
the specialization to which the declaration refers. Specifically, this is done
for explicit instantiations\iref{temp.explicit}, explicit specializations\iref{temp.expl.spec},
and certain friend declarations\iref{temp.friend}. This is also done to
determine whether a deallocation function template specialization matches a placement
\tcode{operator new}\iref{basic.stc.dynamic.deallocation,expr.new}.
In all these cases, \tcode{P} is the type of the function template being considered
as a potential match and \tcode{A} is either the function type from the
declaration
or the type of the deallocation function that would match the placement
\tcode{operator new} as described in~\ref{expr.new}. The
deduction is done as described in~\ref{temp.deduct.type}.

\pnum
If, for the set of function templates so considered, there is either no match or
more than one match after partial ordering has been considered\iref{temp.func.order},
deduction fails and, in the declaration cases, the
program is ill-formed.

\rSec2[temp.over]{Overload resolution}

\pnum
\indextext{overloading!resolution!function template}%
When a call of a function or function template
is written (explicitly, or implicitly using the
operator notation), template argument deduction\iref{temp.deduct}
and checking of any explicit template arguments\iref{temp.arg} are performed
for each function template to find the template argument values (if any) that
can be used with that function template to instantiate a function template
specialization that can be invoked with the call arguments or,
for conversion function templates, that can convert to the required type.
For each function template:
\begin{itemize}
\item If the argument deduction and checking succeeds, the
\grammarterm{template-argument}{s}
(deduced and/or explicit)
are used to synthesize the declaration of
a single function template specialization which is
added to the candidate functions set to be used in overload resolution.
\item If the argument deduction fails or
the synthesized function template specialization would be ill-formed,
no such function is added to the set of candidate functions for that template.
\end{itemize}
The complete set of candidate functions includes all the synthesized
declarations and all of the non-template functions found by name lookup.
The synthesized declarations are
treated like any other functions in
the remainder of overload resolution, except as explicitly noted
in~\ref{over.match.best}.
\begin{footnote}
The parameters of function template
specializations contain no
template parameter types.
The set of conversions allowed on deduced arguments is limited, because the
argument deduction process produces function templates with parameters that
either match the call arguments exactly or differ only in ways that can be
bridged by the allowed limited conversions.
Non-deduced arguments allow the full range of conversions.
Note also that~\ref{over.match.best} specifies that a non-template function will
be given preference over a template specialization if the two functions
are otherwise equally good candidates for an overload match.
\end{footnote}

\pnum
\begin{example}
\begin{codeblock}
template<class T> T max(T a, T b) { return a>b?a:b; }

void f(int a, int b, char c, char d) {
  int m1 = max(a,b);            // \tcode{max(int a, int b)}
  char m2 = max(c,d);           // \tcode{max(char a, char b)}
  int m3 = max(a,c);            // error: cannot generate \tcode{max(int,char)}
}
\end{codeblock}

Adding the non-template function
\begin{codeblock}
int max(int,int);
\end{codeblock}
to the example above would resolve the third call, by providing a function that
can be called for
\tcode{max(a,c)}
after using the standard conversion of
\tcode{char}
to
\tcode{int}
for
\tcode{c}.
\end{example}

\pnum
\begin{example}
Here is an example involving conversions on a function argument involved in
template argument deduction:
\begin{codeblock}
template<class T> struct B { @\commentellip@ };
template<class T> struct D : public B<T> { @\commentellip@ };
template<class T> void f(B<T>&);

void g(B<int>& bi, D<int>& di) {
  f(bi);            // \tcode{f(bi)}
  f(di);            // \tcode{f((B<int>\&)di)}
}
\end{codeblock}
\end{example}

\pnum
\begin{example}
Here is an example involving conversions on a function argument not involved in
template argument deduction:
\begin{codeblock}
template<class T> void f(T*,int);       // \#1
template<class T> void f(T,char);       // \#2

void h(int* pi, int i, char c) {
  f(pi,i);          // \#1: \tcode{f<int>(pi,i)}
  f(pi,c);          // \#2: \tcode{f<int*>(pi,c)}

  f(i,c);           // \#2: \tcode{f<int>(i,c);}
  f(i,i);           // \#2: \tcode{f<int>(i,char(i))}
}
\end{codeblock}
\end{example}

\pnum
Only the signature of a function template specialization is needed to enter the
specialization in a set of candidate functions.
Therefore only the function template declaration is needed to resolve a call
for which a template specialization is a candidate.
\begin{example}
\begin{codeblock}
template<class T> void f(T);    // declaration

void g() {
  f("Annemarie");               // calls \tcode{f<const char*>}
}
\end{codeblock}

The call to
\tcode{f}
is well-formed even if the template
\tcode{f}
is only declared and not defined at the point of the call.
The program will be ill-formed unless a specialization for
\tcode{f<const char*>}
is explicitly instantiated in some translation unit\iref{temp.pre}.
\end{example}

\indextext{template|)}
