______________________________________________________________________
14 Templates [temp]
______________________________________________________________________
1
+------- BEGIN BOX 1 -------+
Template Compilation Model
2 In Santa Cruz, X3J16 were in favour of specifying the model for compi
lation of templates by removing support from the WP for "separate com
pilation" of function templates. However, no consensus could be
reached within WG21 on this issue. It was agreed to add the proposed
working paper wording from N0875 = 96-0057 into the WP as editorial
boxes pending a definite vote in Stockholm based on further technical
evaluation of both models.
3 Two subsequent editorial boxes appear (in _temp.explicit_ and
_temp.point_) detailing the changes that would be required if the vote
in Stockholm formally adopts N0875 = 96-0057. Each box is clearly
labeled "Template Compilation Model" (like this introductory box).
+------- END BOX 1 -------+
A template defines a family of types or functions.
template-declaration:
template < template-parameter-list > declaration
template-parameter-list:
template-parameter
template-parameter-list , template-parameter
The declaration in a template-declaration shall declare or define a
function or a class, define a static data member of a class template,
define a member function or a member class of a class template, or
define a member template of a class. A template-declaration is a dec
laration. A template-declaration is also a definition if its declara
tion defines a function, a class, or a static data member.
4 A template-declaration can appear only as a namespace scope or class
scope declaration. In a function template declaration, the declara
tor-id shall be a template-name (i.e., not a template-id). [Note: in
a class template declaration, if the declarator-id is a template-id,
the declaration declares a class template partial specialization
(_temp.class.spec_). ]
5 A template name may have linkage (_basic.link_). A template, a tem
plate explicit specialization (_temp.expl.spec_), a class template
partial specialization, or a guiding declaration (_temp.over.spec_)
shall not have C linkage. If the linkage of one of these is something
other than C or C++, the behavior is implementation-defined. Template
definitions shall obey the one definition rule (_basic.def.odr_).
6 The name of a class template shall not be declared to refer to any
other template, class, function, object, enumeration, enumerator,
namespace, or type in the same scope (_basic.scope_). Except that a
function template can be overloaded either by (non-template) functions
with the same name or by other function templates with the same name
(_temp.over_), a template name declared in namespace scope to have
external linkage shall be unique in that namespace.
14.1 Template parameters [temp.param]
1 The syntax for template-parameters is:
template-parameter:
type-parameter
parameter-declaration
type-parameter:
class identifieropt
class identifieropt = type-id
typename identifieropt
typename identifieropt = type-id
template < template-parameter-list > class identifieropt
template < template-parameter-list > class identifieropt = template-name
There is no semantic difference between class and typename in a tem
plate-parameter. typename followed by an unqualified-id names a tem
plate type parameter. typename followed by a qualified-name denotes
the type in a non-type parameter-declaration. A storage class shall
not be specified in a template-parameter declaration. [Note: a tem
plate parameter may be a class template. For example,
template<class T> class myarray { /* ... */ };
template<class K, class V, template<class T> class C = myarray>
class Map {
C<K> key;
C<V> value;
// ...
};
--end note]
2 A type-parameter defines its identifier to be a type-name (if declared
with class or typename) or template-name (if declared with template)
in the scope of the template declaration. [Note: because of the name
look up rules, a template-parameter that could be interpreted as
either a non-type template-parameter or a type-parameter (because its
identifier is the name of an already existing class) is taken as a
type-parameter. For example,
class T { /* ... */ };
int i;
template<class T, T i> void f(T t)
{
T t1 = i; // template-parameters T and i
::T t2 = ::i; // global namespace members T and i
}
Here, the template f has a type-parameter called T, rather than an
unnamed non-type template-parameter of class T. ]
3 A non-type template-parameter shall have one of the following (option
ally cv-qualified) types:
--integral type, accepting an integral constant expression as an argu
ment,
--enumeration type, accepting an integral constant expression as an
argument,
--pointer to object, accepting an address constant expression desig
nating a named object with external linkage,
--reference to object, accepting an lvalue expression designating a
named object with external linkage,
--pointer to function, accepting an expression of type pointer to
function designating a function with external linkage,
--reference to function, accepting an lvalue expression designating a
function with external linkage,
--pointer to member, accepting an address constant expression desig
nating a named member of a class.
4 [Note: other types are disallowed either explicitly below or implic
itly by the rules governing the form of template-arguments
(_temp.arg_). ] The top-level cv-qualifiers on the template-parameter
are ignored when determining its type.
5 A non-type non-reference template-parameter is not an lvalue. It
shall not be assigned to or in any other way have its value changed.
A non-type non-reference template-parameter cannot have its address
taken. When a non-type non-reference template-parameter is used as an
initializer for a reference, a temporary is always used. [Example:
template<const X& x, int i> void f()
{
i++; // error: change of template-parameter value
&x; // ok
&i; // error: address of non-reference template-parameter
int& ri = i; // error: non-const reference bound to temporary
const int& cri = i; // ok: const reference bound to temporary
}
--end example]
6 A non-type template-parameter shall not be of type void. A non-type
template-parameter shall not be of floating type. [Example:
template<double d> class X; // error
template<double* pd> class Y; // ok
template<double& rd> class Z; // ok
--end example]
7 The notion of "array type decay" does not apply to template-
parameters. [Example:
template<int a[5]> struct S { /* ... */ };
int v[5];
int* p = v;
S<v> x; // fine
S<p> y; // error
--end example]
8 A default template-argument is a type, value, or template specified
after = in a template-parameter. A default template-argument may be
specified for both a type and non-type template-parameter. A default
template-argument may be specified in a class template declaration or
a class template definition. A default template-argument shall not be
specified in a function template declaration or a function template
definition. The set of default template-arguments available for use
with a template in a translation unit shall be provided by the first
declaration of the template in that translation unit.
9 If a template-parameter has a default template-argument, all subse
quent template-parameters shall have a default template-argument sup
plied. [Example:
template<class T1 = int, class T2> class B; // error
--end example]
14.2 Names of template specializations [temp.names]
1 A template specialization (_temp.spec_) can be referred to by a tem
plate-id:
template-id:
template-name < template-argument-list >
template-name:
identifier
template-argument-list:
template-argument
template-argument-list , template-argument
template-argument:
assignment-expression
type-id
template-name
[Note: the name look up rules (_basic.lookup_) are used to associate
the use of a name with a template declaration; that is, to identify a
name as a template-name. ]
2 For a template-name to be explicitly qualified by the template argu
ments, the name must be known to refer to a template.
3 After name look up (_basic.lookup_) finds that a name is a template-
name, if this name is followed by a <, the < is always taken as the
beginning of a template-argument-list and never as a name followed by
the less-than operator. When parsing a template-id, the first non-
nested > is taken as the end of the template-argument-list rather than
a greater-than operator. [Example:
template<int i> class X { /* ... */ };
X< 1>2 > x1; // syntax error
X<(1>2)> x2; // ok
template<class T> class Y { /* ... */ };
Y< X<1> > x3; // ok
Y<X<6>> 1> > x4; // ok: Y< X< (6>>1) > >
--end example]
4 When the name of a member template specialization appears after . or
-> in a postfix-expression, or after :: in a qualified-id that explic
itly depends on a template-argument (_temp.dep_), the member template
name must be prefixed by the keyword template. Otherwise the name is
assumed to name a non-template. [Example:
class X {
public:
template<size_t> X* alloc();
};
void f(X* p)
{
X* p1 = p->alloc<200>();
// ill-formed: < means less than
X* p2 = p->template alloc<200>();
// fine: < starts explicit qualification
}
--end example]
5 If a name prefixed by the keyword template in this way is not the name
of a member function template, the program is ill-formed.
6 A template-id that names a class template specialization is a class-
name (_class_).
14.3 Template arguments [temp.arg]
1 The types of the template-arguments specified in a template-id shall
match the types specified for the template in its template-parameter-
list. [Example:
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 complex<double> dcomplex; // complex is a standard
// library template
Array<dcomplex> v2(30);
Array<dcomplex> v3(40);
v1[3] = 7;
v2[3] = v3.elem(4) = dcomplex(7,8);
--end example] If the use of a template-argument gives rise to an
ill-formed construct in the implicit instantiation of a template spe
cialization, the instantiation is ill-formed.
2 In a template-argument, an ambiguity between a type-id and an expres
sion is resolved to a type-id. [Example:
template<class T> void f();
template<int I> void f();
void g()
{
f<int()>(); // ``int()'' is a type-id: call the first f()
}
--end example]
3 A template-argument for a non-type non-reference template-parameter
shall be an integral constant-expression of integral type, the address
of an object or a function with external linkage, or a non-overloaded
pointer to member. The address of an object or function shall be
expressed as &f, plain f (for function only), or &X::f where f is the
function or object name. In the case of &X::f, X shall be a (possibly
qualified) name of a class and f the name of a static member of X. A
pointer to member shall be expressed as &X::m where X is a (possibly
qualified) name of a class and m is the name of a non-static member of
X. In particular, a string literal (_lex.string_) is not an accept
able template-argument because a string literal is an object with
internal linkage. [Example:
template<class T, char* p> class X {
// ...
X(const char* q) { /* ... */ }
};
X<int,"Studebaker"> x1; // error: string literal as template-argument
char p[] = "Vivisectionist";
X<int,p> x2; // ok
--end example]
4 Addresses of array elements and of non-static class members shall not
be used as template-arguments. [Example:
template<int* p> class X { };
int a[10];
struct S { int m; static int s; } s;
X<&a[2]> x3; // error: address of array element
X<&s.m> x4; // error: address of non-static member
X<&s.s> x5; // error: &S::s must be used
X<&S::s> x6; // ok: address of static member
--end example]
5 A non-type template-parameter that is a reference shall not be bound
to a temporary, an unnamed lvalue, or a named lvalue that does not
have external linkage. [Example:
template<const int& CRI> struct B { /* ... */ };
B<1> b2; // error: temporary required for template argument
int c = 1;
B<c> b1; // ok
--end example]
6 Standard conversions (_conv_) are applied to an expression used as a
template-argument for a non-type template-parameter to bring it to the
type of its corresponding template-parameter. [Example:
template<const int* pci> struct X { /* ... */ };
int ai[10];
X<ai> xi; // array to pointer and qualification conversions
struct Base { /* ... */ };
struct Derived : Base { /* ... */ };
template<Base& b> struct Y { /* ... */ };
Derived d;
Y<d> yd; // derived to base conversion
--end example]
7 An argument to a non-type template-parameter of pointer to function
type shall have exactly the type specified by the template-parameter.
[Note: this allows selection from a set of overloaded functions. ]
[Example:
void f(char);
void f(int);
template<void (*pf)(int)> struct A { /* ... */ };
A<&f> a; // selects f(int)
--end example]
8 If a declaration acquires a function type through a template-argument
of function type and this causes a declaration that does not use the
syntactic form of a function declarator to have function type, the
program is ill-formed. [Example:
template<class T> struct A {
static T t;
};
typedef int function();
A<function> a; // ill-formed: would declare A<function>::t
// as a static member function
--end example]
9 A local type, a type with no linkage or an unnamed type shall not be
used as a template-argument for a template type-parameter. [Example:
void f()
{
struct S { /* ... */ };
X<S> x3; // error: local type used as template-argument
}
--end example]
10For a template-argument of class type, the template definition has no
special access rights to the inaccessible members of the template
argument type. The name of a template-argument shall be accessible at
the point where it is used as a template-argument. [Example:
template<class T> class X { /* ... */ };
class Y {
private:
struct S { /* ... */ };
X<S> x; // ok: S is accessible
};
X<Y::S> y; // error: S not accessible
--end example]
11When default template-arguments are used, a template-argument list can
be empty. In that case the empty <> brackets shall still be used as
the template-argument-list. [Example:
template<class T = char> class String;
String<>* p; // ok: String<char>
String* q; // syntax error
--end example]
12An explicit destructor call (_class.dtor_) for an object that has a
type that is a class template specialization may explicitly specify
the template-arguments. [Example:
template<class T> struct A {
~A();
};
void main() {
A<int>* p;
p->A<int>::~A(); // ok: destructor call
p->A<int>::~A<int>(); // ok: destructor call
}
--end example]
14.4 Type equivalence [temp.type]
1 Two template-ids refer to the same class or function if their template
names are identical, they refer to the same template, their type tem
plate-arguments are the same type and, their non-type template-
arguments have identical values. [Example:
template<class E, int size> class buffer { /* ... */ };
buffer<char,2*512> x;
buffer<char,1024> y;
declares x and y to be of the same type, and
template<class T, void(*err_fct)()> class list { /* ... */ };
list<int,&error_handler1> x1;
list<int,&error_handler2> x2;
list<int,&error_handler2> x3;
list<char,&error_handler2> x4;
declares x2 and x3 to be of the same type. Their type differs from
the types of x1 and x4. ]
14.5 Template declarations [temp.decls]
1 A template-id, that is, the template-name followed by a template-
argument-list shall not be specified in the declaration of a primary
template declaration. [Example:
template<class T1, class T2, int I> class A<T1, T2, I> { }; // error
template<class T1, int I> void sort<T1, I>(T1 data[I]); // error
--end example] [Note: however, this syntax is allowed in class tem
plate partial specializations (_temp.class.spec_). ]
14.5.1 Class templates [temp.class]
1 A class template defines the layout and operations for an unbounded
set of related types. [Example: a single class template List might
provide a common definition for list of int, list of float, and list
of pointers to Shapes. ]
2 [Example: An array class template might be declared like this:
template<class T> class Array {
T* v;
int sz;
public:
explicit Array(int);
T& operator[](int);
T& elem(int i) { return v[i]; }
// ...
};
The prefix template <class T> specifies that a template is being
declared and that a type-name T will be used in the declaration. In
other words, Array is a parameterized type with T as its parameter. ]
3 When a member function, a member class, a static data member or a mem
ber template of a class template is defined outside of the class tem
plate definition, the names of template parameters used in the defini
tion of the member may be different from the template parameter names
used in the class template definition. The template argument list
following the class template name in the member definition shall name
the parameters in the same order as the one used in the member tem
plate parameter list. [Example:
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 example]
+------- BEGIN BOX 2 -------+
Gibbons feels that the above sentence and example are no longer appli
cable after resolution 6.31 from N0890 = 96-0059, that is the follow
ing should now be legal:
template<class T2, class T1> void A::f1() { } //ok
Corfield is not convinced that was the intent of Core III and that we
should make an explicit decision on this (it seems the right thing to
do).
+------- END BOX 2 -------+
14.5.1.1 Member functions of class templates [temp.mem.func]
1 A member function of a class template is implicitly a member function
template with the template-parameters of its class template as its
template-parameters.
2 A member function template may be defined outside of the class tem
plate definition in which it is declared. [Example:
template<class T> class Array {
T* v;
int sz;
public:
explicit Array(int);
T& operator[](int);
T& elem(int i) { return v[i]; }
// ...
};
declares three function templates. The subscript function might be
defined like this:
template<class T> T& Array<T>::operator[](int i)
{
if (i<0 || sz<=i) error("Array: range error");
return v[i];
}
3 The template-argument for Array<T>::operator[]() will be determined by
the Array to which the subscripting operation is applied.
Array<int> v1(20);
Array<dcomplex> v2(30);
v1[3] = 7; // Array<int>::operator[]()
v2[3] = dcomplex(7,8); // Array<dcomplex>::operator[]()
--end example]
14.5.1.2 Member classes of class templates [temp.mem.class]
1 A member class of a class template is implicitly a class template with
the template-parameters of its class template as its template-
parameters.
2 A member class template may be defined outside the class template def
inition in which it is declared. [Note: the member class template
must be defined before the first use of the member which requires an
instantiation (_temp.inst_). For example,
template<class T> struct A {
class B;
};
A<int>::B* b1; // ok: requires A to be defined but not A::B
template<class T> class A<T>::B { };
A<int>::B b2; // ok: requires A::B to be defined
--end note]
14.5.1.3 Static data members of class templates [temp.static]
1 A static data member of a class template is implicitly a static data
member template with the template-parameters of its class template as
its template-parameters. A template definition for such a static data
member may be provided in a namespace scope enclosing the definition
of the static member's class template. [Example:
template<class T> class X {
static T s;
};
template<class T> T X<T>::s = 0;
--end example]
14.5.2 Member templates [temp.mem]
1 A template can be declared within a class or class template; such a
template is called a member template. A member template can be
defined within or outside its class definition or class template defi
nition. A member template of a class template that is defined outside
of its class template definition shall be specified with the template-
parameters of the class template followed by the template-parameters
of the member template. [Example:
template<class T> class string {
public:
template<class T2> int compare(const T2&);
template<class T2> string(const string<T2>& s) { /* ... */ }
// ...
};
template<class T> template<class T2> int string<T>::compare(const T2& s)
{
// ...
}
--end example]
2 A local class shall not have member templates. A member function tem
plate shall not be virtual. A destructor shall not be a member tem
plate.
3 Access control rules apply to member template names (_class.access_).
14.5.3 Friends [temp.friend]
1 A friend function of a class template can be a function template or an
ordinary (non-template) function. [Example:
template<class T> class task {
// ...
friend void next_time();
friend task<T>* preempt(task<T>*);
friend task* prmt(task*); // task is task<T>
friend class task<int>;
// ...
};
Here, next_time() and task<int> become friends of all task classes,
and each task has appropriately typed functions preempt() and prmt()
as friends. The preempt functions might be defined as a template as
follows
template<class T> task<T>* preempt(task<T>* t) { /* ... */ }
--end example]
2 A friend template may be declared within a non-template class. A
friend function template may be defined within a non-template class.
In these cases, all specializations of the class or function template
are friends of the class granting friendship. [Example:
class A {
template<class T> friend class B; // ok
template<class T> friend void f(T){ /* ... */ } // ok
};
--end example]
3 A member of a class template may be declared to be a friend of a non-
template class. In this case, the corresponding member function of
every specialization of the class template is a friend of the class
granting friendship. [Example:
template<class T> struct A {
struct B { };
void f();
};
class C {
template<class T> friend struct A<T>::B;
template<class T> friend void A<T>::f();
};
--end example]
4 [Note: a friend declaration can add a name to an enclosing scope
(_temp.inject_). ]
14.5.4 Class template partial specializations [temp.class.spec]
1 A primary class template declaration is one in which the class tem
plate name is an identifier. A template declaration in which the
class template name is a template-id, is a partial specialization of
the class template named in the template-id. A partial specialization
of a class template provides an alternative definition of the template
that is used instead of the primary definition when the arguments in a
specialization match those given in the partial specialization
(_temp.class.spec.match_). The primary template shall be declared
before any specializations of that template. If a template is par
tially specialized then that partial specialization shall be declared
before the first use of that partial specialization that would cause
an implicit instantiation to take place, in every translation unit in
which such a use occurs. Each class template partial specialization
is a distinct template and definitions shall be provided for the mem
bers of a template partial specialization (_temp.class.spec.mfunc_).
2 [Example:
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
The first declaration declares the primary (unspecialized) class tem
plate. The second and subsequent declarations declare partial
specializations of the primary template. ]
3 The template parameters are specified in the angle bracket enclosed
list that immediately follows the keyword template. For partial spe
cializations, the template argument list is explicitly written immedi
ately following the class template name. For primary templates, this
list is implicitly described by the template parameter list. Specifi
cally, the order of the template arguments is the sequence in which
they appear in the template parameter list. [Example: the template
argument list for the primary template in the example above is <T1,
T2, I>. ] [Note: the template argument list shall not be specified in
the primary template declaration. For example,
template<class T1, class T2, int I> class A<T1, T2, I> { }; // error
--end note]
4 A non-type argument is non-specialized if it is the name of a non-type
parameter. All other non-type arguments are specialized.
5 Within the argument list of a class template partial specialization,
the following restrictions apply:
--A partially specialized non-type argument expression shall not
involve a template parameter of the specialization. [Example:
template <int I, int J> struct B {};
template <int I> struct B<I, I*2> {}; // error
--end example]
--The type of a specialized non-type argument shall not depend on
another type parameter of the specialization. [Example:
template <class T, T t> struct C {};
template <class T> struct C<T, 1>; // error
--end example]
--The argument list of the specialization shall not be identical to
the implicit argument list of the primary template.
6
+------- BEGIN BOX 3 -------+
Unruh: it seems that the following partial specialization should be
ill-formed but the above restrictions do not seem to apply:
template<int I> struct A<int(*)[I+5], int, 5> {};
Corfield: Perhaps the fix is to change the second bullet to say: "The
type of a specialized argument shall not...". I am uncomfortable with
"depend on" being used here anyway, given that we have such a poor
definition of that phrase.
+------- END BOX 3 -------+
The template parameter list of a specialization shall not contain
default template argument values.1)
_________________________
1) There is no way in which they could be used.
14.5.4.1 Matching of class template [temp.class.spec.match]
partial specializations
1 When a class template is used in a context that requires an instantia
tion of the class, it is necessary to determine whether the instantia
tion is to be generated using the primary template or one of the par
tial specializations. This is done by matching the template arguments
of the class template specialization with the template argument lists
of the partial specializations.
--If exactly one matching specialization is found, the instantiation
is generated from that specialization.
--If more than one matching specialization is found, the partial order
rules (_temp.class.order_) are used to determine whether one of the
specializations is more specialized than the others. If none of the
specializations is more specialized than all of the other matching
specializations, then the use of the class template is ambiguous and
the program is ill-formed.
--If no matches are found, the instantiation is generated from the
primary template.
2 A partial specialization matches a given actual template argument list
if the template arguments of the partial specialization can be deduced
from the actual template argument list (_temp.deduct_). [Example:
A<int, int, 1> a1; // uses #1
A<int, int*, 1> a2; // uses #2, T is int, I is 1
A<int, char*, 5> a3; // uses #4, T is char
A<int, char*, 1> a4; // uses #5, T1 is int, T2 is char, I is 1
A<int*, int*, 2> a5; // ambiguous: matches #3 and #5
--end example]
3 A non-type template argument can also be deduced from the value of an
actual template argument of a non-type parameter of the primary tem
plate. [Example: the declaration of a2 above. ]
4 In a type name that refers to a class template specialization, (e.g.,
A<int, int, 1>) the argument list must match the template parameter
list of the primary template. The template arguments of a specializa
tion are deduced from the arguments of the primary template.
14.5.4.2 Partial ordering of class template [temp.class.order]
specializations
1 For two class template partial specializations, the first is at least
as specialized as the second if:
--the type arguments of the first template's argument list are at
least as specialized as those of the second template's argument list
using the ordering rules for function templates (_temp.func.order_),
and
--each non-type argument of the first template's argument list is at
least as specialized as that of the second template's argument list.
2 A non-type argument is at least as specialized as another non-type
argument if:
--both are formal arguments, or
--the first is a value and the second is a formal argument, or
--both are the same value.
3 A class template partial specialization is more specialized than
another if, and only if, it is at least as specialized as the other
class template partial specialization and that class template partial
specialization is not at least as specialized as the first. Otherwise
the two class template partial specializations are unordered.
+------- BEGIN BOX 4 -------+
Unruh: the following example seems to represent an ordered set of par
tial specializations but does not appear to be covered by the above
rules:
template<int I, int J, class T> class X {}; // #1
template<int I, int J> class X<I, J, int> {}; // #2
template<int I> class X<I, I, int> {}; // #3
It seems "obvious" that #3 is more specialized than #2.
+------- END BOX 4 -------+
14.5.4.3 Members of class template [temp.class.spec.mfunc]
specializations
1 The template parameter list of a member of a class template partial
specialization shall match the template parameter list of the class
template partial specialization. The template argument list of a mem
ber of a class template partial specialization shall match the tem
plate argument list of the class template partial specialization. A
class template specialization is a distinct template. The members of
the class template partial specialization are unrelated to the members
of the primary template. Class template partial specialization mem
bers 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 special
ization. An explicit specialization of a member of a class template
partial specialization is declared in the same way as an explicit spe
cialization of the primary template. [Example:
// primary template
template<class T, int I> struct A {
void f();
};
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(); // ill-formed, no definition of f for A<T,2>
// the primary template is not used here
}
--end example]
14.5.5 Function templates [temp.fct]
1 A function template defines an unbounded set of related functions.
[Example: a family of sort functions might be declared like this:
template<class T> class Array { };
template<class T> void sort(Array<T>&);
--end example]
14.5.5.1 Function template overloading [temp.over.link]
1 It is possible to overload function templates so that two different
function template specializations have the same type. [Example:
// file1.c // file2.c
template<class T> template<class T>
void f(T*); void f(T);
void g(int* p) { void h(int* p) {
f(p); // call f(p); // call
// f<int>(int*) // f<int*>(int*)
} }
--end example]
2 Such specializations are distinct functions and do not violate the one
definition rule (_basic.def.odr_).
3 The signature of a function template specialization consists of the
signature of the function template and of the actual template argu
ments (whether explicitly specified or deduced).
4 The signature of a function template consists of its function signa
ture, its return type and its template parameter list. The names of
the template parameters are significant only for establishing the
relationship between the template parameters and the rest of the sig
nature.
14.5.5.2 Partial ordering of function [temp.func.order]
templates
1 Given two function templates, whether one is more specialized than
another can be determined by transforming each template in turn and
using argument deduction (_temp.deduct_) to compare it to the other.
2 The transformation used is:
--For each type template parameter, synthesize a unique type and sub
stitute that for each occurrence of that parameter in the function
parameter list.
--For each non-type template parameter, synthesize a unique value of
the appropriate type and substitute that for each occurrence of that
parameter in the function parameter list.
3 Using the transformed function parameter list, perform argument deduc
tion against the other function template. The transformed template is
at least as specialized as the other if, and only if, the deduction
succeeds and the deduced parameter types are an exact match (so the
deduction does not rely on implicit conversions).
4 A template is more specialized than another if, and only if, it is at
least as specialized as the other template and that template is not at
least as specialized as the first. [Example:
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); // f(const T*) is more specialized than f(T) or f(T*)
float x;
g(x); // Ambiguous: g(T) or g(T&)
A<int> z;
h(z); // h(A<T>&) is more specialized than h(const T&)
const A<int> z2;
h(z2); // h(const T&) is called because h(A<T>&) is not callable
}
--end example]
14.6 Name resolution [temp.res]
1 A name used in a template is assumed not to name a type unless the
applicable name lookup finds a type name or the name is qualified by
the keyword typename. [Example:
// no B declared here
class X;
template<class T> class Y {
class Z; // forward declaration of member class
void f() {
X* a1; // declare pointer to X
T* a2; // declare pointer to T
Y* a3; // declare pointer to Y
Z* a4; // declare pointer to Z
typedef typename T::A TA;
TA* a5; // declare pointer to T's A
typename T::A* a6; // declare pointer to T's A
T::A* a7; // T::A is not a type name:
// multiply T::A by a7
B* a8; // B is not a type name:
// multiply B by a8
}
};
--end example]
2 In a template declaration, a qualified-id depends on a template-
parameter if at least one of the class-names in the qualified-id is
the template-parameter or, is a template-id in which either the tem
plate-name or one of the template-arguments is the template-parameter.
A qualified-name that refers to a type and that depends on a template-
parameter shall be prefixed by the keyword typename to indicate that
the qualified-name denotes a type.
elaborated-type-specifier:
. . .
typename ::opt nested-name-specifier identifier full-template-argument-listopt
. . .
full-template-argument-list:
< template-argument-list >
+------- BEGIN BOX 5 -------+
Unruh: the following example appears to be disallowed:
Y<T*>::B // T is a template-parameter
This clearly "depends on" a template-parameter and therefore requires
typename.
3 Corfield/Gibbons: there are other problems with the definition of
"depends on" and we need to reformulate this in purely syntactic terms
in order to be able to establish (non-)dependency for phase one name
binding without requiring the compiler to perform symbolic manipula
tion of expressions!
template<int I> struct What {
typedef int C;
};
template<int I> struct How {
What< false ? I : 0 >::C c;
};
+------- END BOX 5 -------+
4 If a specialization of a template is instantiated for a set of tem
plate-arguments such that the qualified-name prefixed by typename does
not denote a type, the specialization is ill-formed. The usual quali
fied name lookup (_basic.lookup.qual_) is used to find the qualified-
name even in the presence of typename. [Example:
struct A {
struct X { };
int X;
};
template<class T> void f(T t) {
typename T::X x; // ill-formed: finds the data member X
// not the member type X
}
--end example]
5 Knowing which names are type names allows the syntax of every template
definition to be checked. A diagnostic shall be issued for a syntac
tically ill-formed template definition. [Note: that means that a
diagnostic must be issued even if the template is never instantiated.
] No diagnostic shall be issued for a template definition for which a
valid specialization can be generated. If no valid specialization can
be generated for a syntactically well-formed template definition, and
that template is not instantiated, it is unspecified whether or not an
implementation is required to issue a diagnostic. [Note: if a tem
plate is instantiated, non-syntax errors will be diagnosed according
to the other rules in this Standard. Exactly when these errors are
diagnosed is a quality of implementation issue. ] [Example:
template<class T> class X {
// ...
void f(T t, int i, char* p)
{
t = i; // diagnosed if X::f is instantiated
// and the assignment to t is an error
p = i; // may be diagnosed even if X::f is
// not instantiated
}
void g(T t) {
+; // diagnosed even if X::g is not instantiated
}
};
--end example]
6 Three kinds of names can be used within a template definition:
--The name of the template itself, the names of the template-
parameters (_temp.param_), and names declared within the template
itself.
--Names dependent on a template-argument (_temp.dep_) from scopes
which are visible at the point of a template instantiation.
--Names from scopes which are visible within the template definition.
7 When looking for the declaration of a name used in a template defini
tion, the usual lookup rules (_basic.lookup.unqual_) are applied,
except that the lookup of names dependent on the template arguments
shall be postponed until the actual template argument is known
(_temp.dep_). [Example:
#include <iostream>
using namespace std;
template<class T> class Set {
T* p;
int cnt;
public:
Set();
Set<T>(const Set<T>&);
void printall()
{
for (int i = 0; i<cnt; i++)
cout << p[i] << '\n';
}
// ...
};
in the example, i is the local variable i declared in printall, cnt is
the member cnt declared in Set, and cout is the standard output stream
declared in iostream. However, not every declaration can be found
this way; the resolution of some names must be postponed until the
actual template-arguments are known. For example, even though the
name operator<< is known within the definition of printall() and a
declaration of it can be found in <iostream>, the actual declaration
of operator<< needed to print p[i] cannot be known until it is known
what type T is (_temp.dep_). ]
8 If a name can be bound at the point of the template definition and it
is not a name that depends on a template-argument (as defined in
_temp.dep_), it will be bound at the template definition point and the
binding is not affected by later declarations. [Example:
void f(char);
template<class T> void g(T t)
{
f(1); // f(char)
f(T(1)); // dependent
f(t); // dependent
}
void f(int);
void h()
{
g(2); // will cause one call of f(char) followed
// by two calls of f(int)
g('a'); // will cause three calls of f(char)
}
--end example]
14.6.1 Locally declared names [temp.local]
1 Within the scope of a class template, the unqualified name of the tem
plate, when not followed by <, is equivalent to the name of the tem
plate followed by the template-parameters enclosed in <>. [Example:
the constructor for Set can be referred to as Set() or Set<T>(). ]
Other specializations (_temp.expl.spec_) of the class can be referred
to by explicitly qualifying the template name with the appropriate
template-arguments. [Example:
template<class T> class X {
X* p; // meaning X<T>
X<T>* p2;
X<int>* p3;
};
--end example]
2 Within the scope of a class template specialization, the name of the
specialization is equivalent to the name of the specialization fol
lowed by the template-arguments enclosed in <>. [Example:
template<class T> class Y;
template<> class Y<int> {
Y* p; // meaning Y<int>
};
--end example]
3 The scope of a template-parameter extends from its point of declara
tion until the end of its template. A template-parameter hides any
entity with the same name in the enclosing scope. [Note: this implies
that a template-parameter can be used in the declaration of subsequent
template-parameters and their default arguments but cannot be used in
preceding template-parameters or their default arguments. For exam
ple,
template<class T, T* p, class U = T> class X { /* ... */ };
template<class T> void f(T* p = new T);
This also implies that a template-parameter can be used in the speci
fication of base classes. For example,
template<class T> class X : public Array<T> { /* ... */ };
template<class T> class Y : public T { /* ... */ };
The use of a template-parameter as a base class implies that a class
used as a template-argument must be defined and not just declared when
the class template is instantiated. ]
4 A template-parameter shall not be redeclared within its scope (includ
ing nested scopes). A template-parameter shall not have the same name
as the template name. [Example:
template<class T, int i> class Y {
int T; // error: template-parameter redeclared
void f() {
char T; // error: template-parameter redeclared
}
};
template<class X> class X; // error: template-parameter redeclared
--end example]
5 In the definition of a member of a class template that appears outside
of the class template definition, the name of a member of this tem
plate hides the name of a template-parameter. [Example:
template<class T> struct A {
struct B { /* ... */ };
void f();
};
template<class B> void A<B>::f()
{
B b; // A's B, not the template parameter
}
--end example]
+------- BEGIN BOX 6 -------+
Gibbons suggests that we make this ill-formed instead of allowing the
hiding, in line with the status of redeclaring a function parameter in
the outermost block of a function. Similarly, for the hiding with base
class members below.
+------- END BOX 6 -------+
6 In the definition of a class template or in the definition of a member
of such a template that appears outside of the template definition,
the name of a base class and, if the base class does not depend on a
template-argument, the name of a base class member hides the name of a
template-parameter with the same name. [Example:
struct A {
struct B { /* ... */ };
int a;
int Y;
};
template<class B, class a> struct X : A {
B b; // A's B
a b; // error: A's a isn't a type name
};
--end example]
14.6.2 Dependent names [temp.dep]
1 Some names used in a template definition depend on a template-
argument. Such names are unbound and are looked up at the point of
the template instantiation (_temp.point_) in both the context of the
template definition and the context of the point of instantiation.
+------- BEGIN BOX 7 -------+
Corfield: this is a much weaker statement than the previous wording,
however this area needs much more work. In particular, we need a com
plete definition of "depend" based on syntactic form only.
+------- END BOX 7 -------+
2 A dependent name may depend on a template-argument either explicitly
or implicitly. A name explicitly depends on a template-argument if
--the name is a template-id in which either the template-name or one
of the template-arguments is a template-parameter, or
--the name is a qualified-id, and the name of a qualifier is a tem
plate-parameter or is a template-id which depends on a template-
argument, or
--the name is referred to using a class member access (_expr.ref_) and
the type of the object-expression is not known until the template-
argument is known.
[Example:
template<class T> struct X : B<T> {
typename T::A* pa;
void f(B<T>* pb) {
static int i = B<T>::i;
pb->j++;
}
};
the base class name B<T>, the type name T::A, the names B<T>::i and
pb->j explicitly depend on the template-argument. ]
3 A name implicitly depends on a template-argument if it is a function
name used in a function call and the function call would have a dif
ferent resolution or no resolution if a type, template, or enumerator
mentioned in the template-argument were missing from the program.
+------- BEGIN BOX 8 -------+
Corfield: what is "mentioned"? This needs more work in Core III.
+------- END BOX 8 -------+
4 [Example: this shows a typical dependent operator call:
class Horse { /* ... */ };
ostream& operator<<(ostream&,const Horse&);
void hh(Set<Horse>& h)
{
h.printall();
}
In the call of Set<Horse>::printall(), the meaning of the << operator
used to print p[i] in the definition of Set<T>::printall()
(_temp.res_), is
operator<<(ostream&,const Horse&);
This function takes an argument of type Horse and is called from a
template with a template-parameter T for which the template-argument
is Horse. Because this function depends on a template-argument, the
call is well-formed. ]
5 [Example: some calls that depend on a template-argument type T are:
1)The function called has a parameter that depends on T according to
the type deduction rules (_temp.deduct_). For example, f(T),
f(Array<T>), and f(const T*).
2)The type of the actual argument depends on T. For example, f(T(1)),
f(t), f(g(t)), and f(&t) assuming that t has the type T.
3)A call is resolved by the use of a conversion to T without either an
argument or a parameter of the called function being of a type that
depends on T as specified in (1) and (2). For example,
struct B { };
struct T : B { };
struct X { operator T(); };
void f(B);
void g(X x)
{
f(x); // meaning f( B( x.operator T() ) )
// so the call f(x) depends on T
}
This ill-formed template instantiation uses a function that does not
depend on a template-argument:
template<class T> class Z {
public:
void f() const
{
g(1); // g() not found in Z's context.
// Look again at point of instantiation
}
};
void g(int);
void h(const Z<Horse>& x)
{
x.f(); // error: g(int) called by g(1) does not depend
// on template-argument ``Horse''
}
The call x.f() gives rise to the specialization:
void Z<Horse>::f() { g(1); }
The call g(1) would call g(int), but since that call does not depend
on the template-argument Horse and because g(int) wasn't in scope at
the point of the definition of the template, the call x.f() is ill-
formed.
6 On the other hand:
void h(const Z<int>& y)
{
y.f(); // fine: g(int) called by g(1) depends
// on template-argument ``int''
}
Here, the call y.f() gives rise to the specialization:
void Z<int>::f() { g(1); }
The call g(1) calls g(int), and since that call depends on the tem
plate-argument int, the call y.f() is acceptable even though g(int)
wasn't in scope at the point of the template definition. ]
7 In the definition of a class template or in the definition of a member
of such template that appears outside of the template definition, if a
base class of this template depends on a template-argument, the base
class scope is not examined during name look up until the class tem
plate is instantiated.
+------- BEGIN BOX 9 -------+
Unruh: it appears that names from dependent base classes can only be
referenced with qualified names (otherwise they are considered non-
dependent names) - we should state this explicitly. Corfield: is this
true? I recall the discussions where this was clearly the intent of
Core III but it makes some code very unwieldy.
+------- END BOX 9 -------+
[Example:
typedef double A;
template<class T> B {
typedef int A;
};
template<class T> struct X : B<T> {
A a;
};
X<T>::a has type double. The type name A binds to the typedef name
defined in the global namespace scope, not to the typedef name defined
in the base class B<T>. ]
8 If a template-argument is a used as a base class, a member of that
class cannot hide a name declared within a template, or a name from
the template's enclosing scopes. [Example:
struct A {
struct B { /* ... */ };
int a;
int Y;
};
int a;
template<class T> struct Y : T {
struct B { /* ... */ };
B b; // The B defined in Y
void f(int i) { a = i; } // ::a
Y* p; // Y<T>
};
Y<A> ya;
The members A::B, A::a, and A::Y of the template argument A do not
affect the binding of names in Y<A>. ]
14.6.3 Non-dependent names [temp.nondep]
1 Non-dependent names used in a template definition are found using the
usual name lookup and bound at the point they are used. [Example:
void g(double);
void h();
template<class T> class Z {
public:
void f() {
g(1); // calls g(double)
h++; // error: cannot increment function
}
};
void g(int); // not in scope at the point of the template
// definition, not considered for the call g(1)
--end example]
14.6.4 Point of instantiation [temp.point]
1 The point of instantiation of a template specialization is the point
where names dependent on the template-argument are bound. That point
is in the nearest enclosing namespace scope containing the first use
of the template requiring its definition. All names declared in
namespace scope that are visible at the point of the first use are
visible at the point of instantiation. In particular the name of the
class or function that encloses that use is visible at the point of
instantiation. [Note: this implies that names used in a template def
inition cannot be bound to local names or class member names from the
scope of the template use. They can, however, be bound to names of
namespace members. [Example:
template<class T> class Y {
public:
void f1() const { g1(1); }
void f2() const { g2(2); }
void f3() const { g3(3); }
void f4() const { g4(4); }
};
void k(const Y<int>& h)
{
void g1(int);
h.f1(); // error: g1(int) called by g1(1) not found
// local g1() not considered
}
class C {
void g2(int);
void m(const Y<int>& h)
{
h.f2(); // error: g2(int) called by g2(2) not found
// C::g2() not considered
}
};
namespace N {
void g3(int);
void n(const Y<int>& h)
{
h.f3(); // N::g3(int) called by g3(3)
}
}
void g4(int i)
{
Y<int> h;
h.f4(); // g4(int) called by g4(4)
}
--end example] --end note]
2 The names of functions declared before the point of instantiation,
either from the namespace of the template itself or from the namespace
containing the point of instantiation, are used to resolve function
names that implicitly depend on the template-arguments. Overload res
olution is used to choose between functions with the same name in
these two namespaces. If a name is found in both namespaces and over
load resolution cannot resolve a use, the program is ill-formed.
3 [Example:
namespace NN {
void g(int);
void h(int);
template<class T> void f(T t)
{
g(t);
h(t);
k(t);
}
}
namespace MM {
void g(double);
void k(double);
void m()
{
NN::f(1); // indirectly calls NN::g(int),
// NN::h, and MM::k.
NN::f(1.0); // indirectly calls MM::g(double),
// NN::h, and MM::k.
}
}
--end example]
4 Each translation unit in which the definition of a template is used in
a way that requires an implicit instantiation of a specialization has
a point of instantiation for the template. If this causes names used
in the template definition to bind to different names in different
translation units, the one definition rule (_basic.def.odr_) has been
violated and any use of the template is ill-formed. Such violation
does not require a diagnostic.
14.6.5 Friend names declared within a class [temp.inject]
template
1 Friend classes or functions can be declared within a class template.
When a template is instantiated, the names of its friends are declared
as if the specialization had been explicitly declared at its point of
instantiation. The names of friend classes or functions of a class
template specialization that are first introduced by the friend decla
rations shall only be used after the template use that caused the
instantiation. [Example:
// Assume that Y is not yet declared
template<class T> class X {
friend class Y;
};
Y* py1; // ill-formed: Y is not in scope
void g()
{
X<C>* pc; // does not cause instantiation
Y* py2; // ill-formed: Y is not in scope
X<C> c; // causes instantiation of X<C>, so
// names from X<C> can be used
// here on
Y* py3; // ok
}
Y* py4; // ok
--end example]
+------- BEGIN BOX 10 -------+
Name injection from an implicitly generated template specialization is
under debate. That is, it might be banned or restricted.
+------- END BOX 10 -------+
14.7 Template specialization [temp.spec]
1 A class instantiated from a class template is called an instantiated
class. A function instantiated from a function template is called an
instantiated function. A static data member instantiated from a
static data member template is called an instantiated static data mem
ber. The act of instantiating a class, function, or static data mem
ber from a template is referred to as template instantiation. A class
declaration introduced by template<> is called an explicitly special
ized class. The name of the class in such a definition shall be a
template-id. A function declaration introduced by template<> is
called an explicitly specialized function. The name of the function
in such a declaration may be a template-id. A static data member dec
laration introduced by template<> is called an explicitly specialized
static data member. The name of the class in such a declaration shall
be a template-id.
+------- BEGIN BOX 11 -------+
Corfield: I don't think the above wording is quite right for either
class member templates or class members of class templates.
+------- END BOX 11 -------+
[Example:
template<class T = int> struct A
{
static int x;
};
template<class U> void g(U) { }
template<> struct A<double> { }; // specialize for T == double
template<> struct A<> { }; // specialize for T == int
template<> void g(char) { } // specialize for U == char
// U is deduced from the parameter type
template<> void g<int>(int) { } // specialize for U == int
template<> int A<char>::x = 0; // specialize for T == char
template<> int A<>::x = 1; // specialize for T == int
--end example]
2 An instantiated template specialization can be either implicitly
instantiated (_temp.inst_) for a given argument list or be explicitly
instantiated (_temp.explicit_). A specialization is a class, func
tion, or static data member that is either instantiated or explicitly
specialized (_temp.expl.spec_). A template that has been used in a
way that requires a specialization of its definition causes the spe
cialization to be implicitly instantiated unless it has been either
explicitly instantiated or explicitly specialized.
3 No program shall explicitly instantiate any template more than once,
both explicitly instantiate and explicitly specialize a template, or
specialize a template more than once for a given set of template-
arguments. An implementation is not required to diagnose a violation
of this rule.
+------- BEGIN BOX 12 -------+
Template Compilation Model
4 If the definition of a function template or static data member tem
plate that is neither explicitly instantiated nor explicitly special
ized is not present in every translation unit in which it is used, the
results are undefined. [Note: it is expected that violation of this
rule will result in a failure to link the program on certain implemen
tations. --end note]
+------- END BOX 12 -------+
5 Each class template specialization instantiated from a template has
its own copy of any static members. [Example:
template<class T> class X {
static T s;
// ...
};
template<class T> T X<T>::s = 0;
X<int> aa;
X<char*> bb;
X<int> has a static member s of type int and X<char*> has a static
member s of type char*. ]
14.7.1 Implicit instantiation [temp.inst]
1 Unless a class template specialization has been explicitly instanti
ated (_temp.explicit_) or explicitly specialized (_temp.expl.spec_),
the class template specialization is implicitly instantiated when the
specialization is referenced in a context that requires a completely-
defined object type. Unless a function template specialization has
been explicitly instantiated or explicitly specialized, the function
template specialization is implicitly instantiated when the special
ization is referenced in a context that requires a function definition
to exist. Unless a static data member template has been explicitly
instantiated or explicitly specialized, the static data member tem
plate specialization is implicitly instantiated when the specializa
tion is used in a way that requires a definition for the static data
member.
2 [Example:
template<class T> class Z {
public:
void f();
void g();
};
void h()
{
Z<int> a; // instantiation of class Z<int> required
Z<char>* p; // instantiation of class Z<char> not
// required
Z<double>* q; // instantiation of class Z<double>
// not required
a.f(); // instantiation of Z<int>::f() required
p->g(); // instantiation of class Z<char> required, and
// instantiation of Z<char>::g() required
}
Nothing in this example requires class Z<double>, Z<int>::g(), or
Z<char>::f() to be implicitly instantiated. ]
3 If a class template for which a definition is in scope is used in a
way that involves overload resolution, conversion to a base class, or
pointer to member conversion, the class template specialization is
implicitly instantiated. [Example:
template<class T> class B { /* ... */ };
template<class T> class D : public B<T> { /* ... */ };
void f(void*);
void f(B<int>*);
void g(D<int>* p, D<char>* pp)
{
f(p); // instantiation of D<int> required: call f(B<int>*)
B<char>* q = pp; // instantiation of D<char> required:
// convert D<char>* to B<char>*
}
--end example]
+------- BEGIN BOX 13 -------+
Unruh believes the above paragraph does not precisely enumerate all
the situations in which templates are required to be instantiated.
+------- END BOX 13 -------+
4 If an implicit instantiation of a class template specialization is
required and the template is declared but not defined, the program is
ill-formed. [Example:
template<class T> class X;
X<char> ch; // error: definition of X required
--end example]
5 If a function template for which a declaration is in scope is used in
a way that involves overload resolution, a declaration of a function
template specialization is implicitly instantiated (_temp.over_).
6 An implementation shall not implicitly instantiate a function, non-
virtual member function, class or member template that does not
require instantiation. It is unspecified whether or not an implemen
tation implicitly instantiates a virtual member function that does not
require specialization.
7 Implicitly instantiated class template, function, and static data mem
ber specializations are placed in the namespace where the template was
defined. [Example:
namespace N {
template<class T> class List {
public:
T* get();
// ...
};
}
template<class K, class V> class Map {
N::List<V> lt;
V get(K);
// ...
};
void g(Map<char*,int>& m)
{
int i = m.get("Nicholas");
// ...
}
a call of lt.get() from Map<char*,int>::get() would place
List<int>::get() in the namespace N rather than in the global names
pace. ]
8 [Note: _temp.point_ defines the point of instantiation of a template
specialization. ]
9 If a virtual function is implicitly instantiated, its point of instan
tiation is immediately following the point of instantiation for its
class.
10The point of instantiation for a template used inside another template
and not instantiated previous to an instantiation of the enclosing
template is immediately before the point of instantiation of the
enclosing template.
11There shall be an implementation-defined quantity that specifies the
limit on the depth of recursive instantiations. The result of an
infinite recursion in instantiation is undefined. [Example:
template<class T> class X {
X<T>* p; // ok
X<T*> a; // implicit generation of X<T> requires
// the implicit instantiation of X<T*> which requires
// the implicit instantiation of X<T**> which ...
};
--end example]
14.7.2 Explicit instantiation [temp.explicit]
1 A class, function or static data member specialization can be explic
itly instantiated from its template.
2 The syntax for explicit instantiation is:
explicit-instantiation:
template declaration
where the unqualified-id in the declaration shall be either a tem
plate-id or, where all template arguments can be deduced, a template-
name. [Note: the declaration may declare a qualified-id, in which
case the unqualified-id of the qualified-id must be a template-id. ]
[Example:
template<class T> class Array { /* ... */ };
template class Array<char>;
template<class T> void sort(Array<T>& v) { /* ... */ }
template void sort(Array<char>&); // argument is deduced here
namespace N {
template<class T> void f(T&) { }
}
template void N::f<int>(int&);
--end example]
3 A declaration of a function template shall be in scope at the point of
an explicit instantiation of the function template. A definition of
the class template shall be in scope at the point of the explicit
instantiation of the class template. A definition of the static data
member template shall be in scope at the point of the explicit instan
tiation of the static data member template. If the declaration names
a compiler-generated function, the program is ill-formed.
+------- BEGIN BOX 14 -------+
Template Compilation Model
4 The definition of a function template or static data member template
shall be present in every translation unit in which it is explicitly
instantiated.
+------- END BOX 14 -------+
+------- BEGIN BOX 15 -------+
Unruh: should explicit instantiation define exactly one instantiation
point? Corfield: this depends on the specification chosen for the
template compilation model - in particular, if explicit instantiation
defines exactly one instantiation point, what impact would be the
impact of removing separate compilation of templates (i.e., how would
an implementation know where the single instantiation point was?).
+------- END BOX 15 -------+
5 An explicit instantiation of a template specialization is in the scope
of the namespace in which the template was defined. [Example:
namespace N {
template<class T> class Y { /* ... */ };
}
template class Y<int>; // error: class template Y not visible
// in the global namespace
using N::Y;
template class Y<int>; // ok: explicit instantiation in namespace N
template class N::Y<char*>; // ok: explicit instantiation in namespace N
--end example]
6 A trailing template-argument can be left unspecified in an explicit
instantiation of a function template specialization provided it can be
deduced from the function argument type (_temp.deduct_). [Example:
template<class T> class Array { /* ... */ };
template<class T> void sort(Array<T>& v);
// instantiate sort(Array<int>&) - template-argument deduced
template void sort<>(Array<int>&);
--end example]
7 The explicit instantiation of a class template specialization implies
the instantiation of all of its members not previously explicitly spe
cialized in the translation unit containing the explicit instantia
tion. A member class of a class template may be explicitly instanti
ated.
8 The usual access checking rules do not apply to explicit instantia
tions. [Note: In particular, the template arguments and names used in
the function declarator (including parameter types, return types and
exception specifications) may be private types or objects which would
normally not be accessible and the template may be a member template
or member function which would not normally be accessible. ]
14.7.3 Explicit specialization [temp.expl.spec]
1 An explicit specialization of any of the following:
--function template
--class template
--member function of a class template
--static data member of a class template
--member class of a class template
--member class template of a class template
--member function template of a class template
can be declared by a declaration introduced by template<>; that is:
specialization:
template < > declaration
[Example:
template<class T> class stream;
template<> class stream<char> { /* ... */ };
template<class T> class Array { /* ... */ };
template<class T> void sort(Array<T>& v) { /* ... */ }
template<> void sort<char*>(Array<char*>&) ;
Given these declarations, stream<char> will be used as the definition
of streams of chars; other streams will be handled by class template
specializations instantiated from the class template. Similarly,
sort<char*> will be used as the sort function for arguments of type
Array<char*>; other Array types will be sorted by functions generated
from the template. ]
2 Default function arguments shall not be specified in a declaration or
a definition of an explicit specialization.
3 A declaration of the template being explicitly specialized shall be in
scope at the point of declaration of an explicit specialization. If
the declaration names a implicitly-declared special member function
(_special_), the program is ill-formed. [Note: a declaration, but not
a definition of the template is required. ] [Example:
template<> class X<int> { /* ... */ }; // error: X not a template
template<class T> class X;
template<> class X<char*> { /* ... */ }; // fine: X is a template
--end example]
4 If a template is explicitly specialized then that specialization shall
be declared before the first use of that specialization that would
cause an implicit instantiation to take place, in every translation
unit in which such a use occurs. [Example:
template<class T> class Array { /* ... */ };
template<class T> void sort(Array<T>& v) { /* ... */ }
void f(Array<String>& v)
{
sort(v); // use general template
// sort(Array<T>&), T is String
}
template<> void sort<String>(Array<String>& v); // error: specialize after use
template<> void sort<>(Array<char*>& v); // fine sort<char*> not yet used
--end example] If a function, class or static data member template
has been explicitly specialized for a template-argument-list, no spe
cialization shall be implicitly instantiated for that template-
argument-list.
5 A template explicit specialization is in the scope of the namespace in
which the template was defined. [Example:
namespace N {
template<class T> class X { /* ... */ };
template<class T> class Y { /* ... */ };
template<> class X<int> { /* ... */ }; // ok: specialization
// in same namespace
}
template<> class N::Y<double> { /* ... */ }; // ok: specialization
// in namespace N
--end example]
6 A template-id that names a class template explicit specialization that
has been declared but not defined can be used exactly like the names
of other incompletely-defined classes (_basic.types_). [Example:
template<class T> class X; // X is a class template
template<> class X<int>;
X<int>* p; // ok: pointer to declared class X<int>
X<int> x; // error: object of incomplete class X<int>
--end example]
7 A trailing template-argument can be left unspecified in an explicit
function template specialization provided it can be deduced from the
function argument type. [Example:
template<class T> class Array { /* ... */ };
template<class T> void sort(Array<T>& v);
// explicit specialization for sort(Array<int>&)
// with deduces template-argument of type int
template<> void sort(Array<int>&);
--end example]
8 It is possible for a specialization with a given function signature to
be instantiated from more than one function template. In such cases,
explicit specification of the template arguments must be used to
uniquely identify the function template specialization being special
ized. [Example:
template <class T> void f(T);
template <class T> void f(T*);
template <> void f(int*); // Ambiguous
template <> void f<int>(int*); // OK
template <> void f(int); // OK
--end example]
9 A function with the same name as a template and a type that exactly
matches that of a template specialization is not an explicit special
ization (_temp.over.spec_).
10An explicit specialization of a function template is inline or static
only if it is explicitly declared to be, and independently of whether
its function template is. [Example:
template<class T> void f(T) { /* ... */ }
template<class T> inline T g(T) { /* ... */ }
template<> inline void f<>(int) { /* ... */ } // ok: inline
template<> int g<>(int) { /* ... */ } // ok: not inline
--end example]
11Member function templates, member class templates of non-template
classes and class template specializations may be specialized in the
same manner as function templates and class templates.
12A specialization of a member function template or member class tem
plate of a non-specialized class template is itself a template.
13An explicit specialization of a static data member of a template is a
definition if the declaration includes an initializer; otherwise, it
is a declaration. [Note: there is no syntax for the definition of a
static data member of a template that requires default initialization.
template<> X Q<int>::x;
This is a declaration regardless of whether X can be default initial
ized (_dcl.init_). ]
14A member template of a class template may be explicitly specialized
for a given implicit instantiation of the class template, even if the
member template is defined in the class template definition. An
explicit specialization of a member template is specified using the
template specialization syntax. Default function arguments shall not
be supplied in such declarations. [Example:
template<class T> struct A {
void f(T);
template<class X> void g(T,X);
void h(T) { }
};
// specialization
template<> void A<int>::f(int);
// out of class member template definition
template<class T> template<class X> void A<T>::g(T,X) { }
// member template partial specialization
template<> template<class X> void A<int>::g(int,X);
// member template specialization
template<> template<>
void A<int>::g(int,char); // X deduced as char
template<> template<>
void A<int>::g<char>(int,char); // X specified as char
// member specialization even if defined in class definition
template<> void A<int>::h(int) { }
--end example]
15A member template of an explicitly specialized class shall not be
implicitly instantiated from the general template. Instead, the mem
ber template shall itself be explicitly specialized. [Example:
template<class T> struct A {
void f(T) { /* ... */ }
};
template<> struct A<int> {
void f(int);
};
void h()
{
A<int> a;
a.f(16); // A<int>::f must be defined somewhere
}
template<> void A<int>::f() { /* ... */ }
--end example] Thus, an explicit specialization of a class template
implies the declaration of specializations of all of its members. The
definition of each such specialized member which is used shall be pro
vided in some translation unit.
14.8 Function template specializations [temp.fct.spec]
1 A function instantiated from a function template is called a function
template specialization; so is an explicit specialization of a func
tion template. Template arguments can either be explicitly specified
in a call or be deduced (_temp.deduct_) from the function arguments.
2 Each function template instantiated from a template has its own copy
of any static variable. [Example:
template<class T> f(T* p)
{
static T s;
// ...
};
void g(int a, char* b)
{
f(&a); // call f<int>(int*)
f(&b); // call f<char*>(char**)
}
Here f<int>(int*) has a static variable s of type int and
f<char*>(char**) has a static variable s of type char*. ]
14.8.1 Explicit template argument [temp.arg.explicit]
specification
1 Template arguments can be specified in a call by qualifying the func
tion template specialization name by the list of template-arguments
exactly as template-arguments are specified in uses of a class tem
plate specialization. [Example:
template<class T> void sort(Array<T>& v);
void f(Array<dcomplex>& cv, Array<int>& ci)
{
sort<dcomplex>(cv); // sort(Array<dcomplex>&)
sort<int>(ci); // sort(Array<int>&)
}
and
template<class U, class V> U convert(V v);
void g(double d)
{
int i = convert<int,double>(d); // int convert(double)
char c = convert<char,double>(d); // char convert(double)
}
--end example]
2 Trailing arguments that can be deduced (_temp.deduct_) may be omitted
from the list of explicit template-arguments. [Example:
template<class X, class Y> X f(Y);
void g()
{
int i = f<int>(5.6); // Y is deduced to be double
int j = f(5.6); // ill-formed: X cannot be deduced
}
--end example]
3 Implicit conversions (_conv_) will be performed on a function argument
to bring it to the type of the corresponding function parameter if the
parameter type is fixed by an explicit specification of a template-
argument. [Example:
template<class T> void f(T);
class Complex {
// ...
Complex(double);
};
void g()
{
f<Complex>(1); // ok, means f<Complex>(Complex(1))
}
--end example]
14.8.2 Template argument deduction [temp.deduct]
1 Template arguments that can be deduced from the function arguments of
a call need not be explicitly specified. [Example:
void f(Array<dcomplex>& cv, Array<int>& ci)
{
sort(cv); // call sort(Array<dcomplex>&)
sort(ci); // call sort(Array<int>&)
}
and
void g(double d)
{
int i = convert<int>(d); // call convert<int,double>(double)
int c = convert<char>(d); // call convert<char,double>(double)
}
--end example] [Note: if a template-parameter is only used to repre
sent a function template return type, its corresponding template-
argument cannot be deduced and the template-argument must be explic
itly specified. ]
2 Type deduction is done for each function template argument that is not
explicitly specified. The type of the parameter of the function tem
plate (call it P) is compared to the type of the corresponding argu
ment of the call (call it A), and an attempt is made to find a type
for the template type argument, a template for the template template
argument or a value for the template non-type argument, that will make
P after substitution of the deduced type or value (call that the
deduced A) compatible with the call argument. Type deduction is done
independently for each parameter/argument pair, and the deduced tem
plate argument types, templates and values are then combined. If type
deduction cannot be done for any parameter/argument pair, or if for
any parameter/argument pair the deduction leads to more than one pos
sible set of deduced types, templates or values, or if different
parameter/argument pairs yield different deduced types, templates or
values for a given template argument, or if any template argument
remains neither deduced nor explicitly specified, template argument
deduction fails.
3 If P is not a reference type:
--if A is an array type, the pointer type produced by the array-to-
pointer standard conversion (_conv.array_) is used in place of A for
type deduction; otherwise,
--if A is a function type, the pointer type produced by the function-
to-pointer standard conversion (_conv.func_) is used in place of A
for type deduction; otherwise,
--if A is a cv-qualified type, the top level cv-qualifiers of A's type
are ignored for type deduction.
If P is a cv-qualified type, the top level cv-qualifiers of P's type
are ignored for type deduction. If P is a reference type, the type
referred to by P is used in place of P for type deduction.
4 In general, the deduction process attempts to find template argument
values that will make the deduced A identical to A (after the type A
is transformed as described above). However, there are three cases
that allow a difference:
--If the original P is a reference type, the deduced A (i.e., the type
referred to by the reference) can be more cv-qualified than A.
--If P is a pointer or pointer to member type, A can be another
pointer or pointer to member type that can be converted to the
deduced A via a qualification conversion (_conv.qual_).
--If P is a class, and P has the form class-template-name<arguments>,
A can be a derived class of the deduced A. Likewise, if P is a
pointer to a class of the form class-template-name<arguments>, A can
be a pointer to a derived class pointed to by the deduced A.
These alternatives are considered only if type deduction cannot be
done otherwise. If they yield more than one possible deduced A, the
type deduction fails. When deducing arguments in the context of tak
ing the address of an overloaded function (_over.over_), these inexact
deductions are not considered.
5 [Example: here is an example in which different parameter/argument
pairs produce inconsistent template argument deductions:
template<class T> void f(T x, T y) { /* ... */ }
struct A { /* ... */ };
struct B : A { /* ... */ };
int g(A a, B b)
{
f(a,b); // error: T could be A or B
f(b,a); // error: T could be A or B
f(a,a); // ok: T is A
f(b,b); // ok: T is B
}
6 Here is an example where a qualification conversion applies between
the argument type on the function call and the deduced template argu
ment type:
template<class T> void f(const T*) {}
int *p;
void s()
{
f(p); // f(const int *)
}
7 Here is an example where the template argument is used to instantiate
a derived class type of the corresponding function parameter type:
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 main()
{
D<int> d;
D2 d2;
f(d); // calls f(B<int>&)
f(d2); // calls f(B<int>&)
}
--end example]
8 A template type argument T, a template template argument TT or a tem
plate non-type argument i can be deduced if P and A have one of the
following forms:
T
cv-list T
T*
T&
T[integer-constant]
class-template-name<T>
type(*)(T)
T(*)()
T(*)(T)
type T::*
T type::*
T (type::*)()
type (T::*)()
type (type::*)(T)
type[i]
class-template-name<i>
TT<T>
TT<i>
TT<>
where (T) represents argument lists where at least one argument type
contains a T, and () represents argument lists where no parameter con
tains a T. Similarly, <T> represents template argument lists where at
least one argument contains a T, <i> represents template argument
lists where at least one argument contains an i and <> represents tem
plate argument lists where no argument contains a T or an i.
+------- BEGIN BOX 16 -------+
Corfield: the permissible forms need to be reviewed - the list is not
complete and is not a particularly useful way to decide whether a
given form is allowed, despite the following text about composition of
types.
+------- END BOX 16 -------+
These forms can be used in the same way as T is for further composi
tion of types. [Example:
X<int> (*)(char[6])
is of the form
class-template-name<T> (*)(type[i])
which is a variant of
type (*)(T)
where type is X<int> and T is char[6]. ]
9 Template arguments cannot be deduced from function arguments involving
constructs other than the ones specified above.
10A template type argument cannot be deduced from the type of a non-type
template-argument. [Example:
template<class T, T i> void f(double a[10][i]);
int v[10][20];
f(v); // error: argument for template-parameter T cannot be deduced
--end example]
11[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:
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: i deduced to be 20
f1<10>(v); // ok
f2(v); // error: cannot deduce template-argument i
f2<10>(v); // ok
f3(v); // ok: i deduced to be 10
}
--end note]
12If, in the declaration of a function template with a non-type tem
plate-parameter, the non-type template-parameter is used in an expres
sion in the function parameter-list, the corresponding template-
argument shall always be explicitly specified because type deduction
would otherwise always fail for such a template-argument. [Example:
template<int i> class A { /* ... */ };
template<short s> void g(A<s+1>);
void k() {
A<1> a;
g(a); // error: deduction fails for expression s+1
g<0>(a); // ok
}
--end example]
13If, in the declaration of a function template with a non-type tem
plate-parameter, the non-type template-parameter is used in an expres
sion in the function parameter-list and, if the corresponding tem
plate-argument is deduced, the template-argument type shall match the
type of the template-parameter exactly, except that a template-
argument deduced from an array bound may be of any integral type.2)
[Example:
template<int i> class A { /* ... */ };
template<short s> void f(A<s>);
void k1() {
A<1> a;
f(a); // error: deduction fails for conversion from int to short
f<1>(a); // ok
}
_________________________
2) Although the template-argument corresponding to a template-
parameter of type bool may be deduced from an array bound, the result
ing value will always be true because the array bound will be non-
zero.
template<const short cs> class B { };
template<short s> void h(B<s>);
void k2() {
B<1> b;
g(b); // ok: cv-qualifiers are ignored on template parameter types
}
--end example]
14A template-argument can be deduced from a pointer to function or
pointer to member function argument if the set of overloaded functions
does not contain function templates and at most one of a set of over
loaded functions provides a unique match. [Example:
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 h(char,int) is a unique match
f(&foo); // error: type deduction fails because foo is a template
}
--end example]
15If function template-arguments are explicitly specified in a call,
they shall be specified in declaration order of their corresponding
template-parameters. Trailing arguments can be left out of a list of
explicit template-arguments. [Example:
template<class X, class Y, class Z> X f(Y,Z);
void g()
{
f<int,char*,double>("aa",3.0);
f<int,char*>("aa",3.0); // Z is deduced to be double
f<int>("aa",3.0); // Y is deduced to be char*, and
// Z is deduced to be double
f("aa",3.0); // error: X cannot be deduced
}
--end example]
16A template type-parameter cannot be deduced from the type of a func
tion default argument. [Example:
template <class T> void f(T = 5, T = 7);
void g()
{
f(1); // ok: call f<int>(1,7)
f(); // error: cannot deduce T
f<int>(); // ok: call f<int>(5,7)
}
--end example]
17The template-argument corresponding to a template template-parameter
is deduced from the type of the template-argument of a class template
specialization used in the argument list of a function call. [Exam
ple:
template <template X<class T> > struct A { };
template <template X<class T> > void f(A<X>) { }
template<class T> struct B { };
A<B> ab;
f(ab); // calls f(A<B>)
--end example]
18If trailing template-arguments are left unspecified in a function tem
plate explicit instantiation or explicit specialization
(_temp.explicit_, _temp.expl.spec_), the template arguments can be
deduced from the function parameters according to the rules specified
in this subclause. [Note: a default template-argument cannot be spec
ified in a function template declaration or definition; therefore
default template-arguments cannot be used to influence template argu
ment deduction. ]
14.8.3 Overload resolution [temp.over]
1 A function template can be overloaded either by (non-template) func
tions of its name or by (other) function templates of that same name.
When a call to that name is written (explicitly, or implicitly using
the operator notation), template argument deduction (_temp.deduct_) is
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. For each function template, if the argument
deduction succeeds, the deduced template-arguments are used to instan
tiate a single function template specialization which is added to the
candidate functions set to be used in overload resolution. If, for a
given function template, argument deduction fails, no such function is
added to the set of candidate functions for that template. The com
plete set of candidate functions includes all the function templates
instantiated in this way and all of the non-template overloaded func
tions of the same name. The function template specializations are
treated like any other functions in the remainder of overload resolu
tion, except as explicitly noted.3)
2 [Example:
_________________________
3) The parameters of function template specializations contain no tem
plate parameter types. The set of conversions allowed on deduced ar
guments is limited, because the argument deduction process produces
function templates with parameters that either match the call argu
ments exactly or differ only in ways that can be bridged by the al
lowed limited conversions. Non-deduced arguments allow the full range
of conversions.
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); // max(int a, int b)
char m2 = max(c,d); // max(char a, char b)
int m3 = max(a,c); // error: cannot generate max(int,char)
}
3 Adding
int max(int,int);
to the example above would resolve the third call, by providing a
function that could be called for max(a,c) after using the standard
conversion of char to int for c.
4 Here is an example involving conversions on a function argument
involved in template-argument deduction:
template<class T> struct B { /* ... */ };
template<class T> struct D : public B<T> { /* ... */ };
template<class T> void f(B<T>&);
void g(B<int>& bi, D<int>& di)
{
f(bi); // f(bi)
f(di); // f( (B<int>&)di )
}
5 Here is an example involving conversions on a function argument not
involved in template-parameter deduction:
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: f<int>(pi,i)
f(pi,c); // #2: f<int*>(pi,c)
f(i,c); // #2: f<int>(i,c);
f(i,i); // #2: f<int>(i,char(i))
}
--end example]
6 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. [Example:
template<class T> void f(T); // declaration
void g()
{
f("Annemarie"); // call of f<char*>
}
The call of f is well-formed even if the template f is only declared
and not defined at the point of the call. The program will be ill-
formed unless a specialization for f<char*>, either implicitly or
explicitly generated, is present in some translation unit. ]
+------- BEGIN BOX 17 -------+
Unruh: the exact wording may be affected by the choice of template
compilation model.
+------- END BOX 17 -------+
14.8.4 Overloading and template specializations [temp.over.spec]
1 A function template can be overloaded by a function with the same type
as a potentially instantiated function template specialization.
[Example:
template<class T> T max(T a, T b) { return a>b?a:b; }
int max(int a, int b);
int min(int a, int b);
template<class T> T min(T a, T b) { return a<b?a:b; }
--end example] Such an overloaded function is a specialization but
not an explicit specialization. The declaration simply guides the
overload resolution.
+------- BEGIN BOX 18 -------+
Unruh: it is not clear whether the template declaration must be in
scope prior to the declaration of the guiding function.
+------- END BOX 18 -------+
[Note: this implies that a definition of max(int,int) and min(int,int)
will be implicitly instantiated from the templates. ]
2 Defining a function with the same name and in the same scope as a tem
plate specialization that is used is ill-formed; no diagnostic is
required if the template specialization and the function are declared
in different translation units. [Example:
template<class T> T max(T a, T b) { return a>b?a:b; }
int max(int a, int b) { return a>b?a:b; }
void f(int x, int y)
{
max(x,y); // error: duplicate definition of max()
}
--end example] [Note: if the conversions enabled by an ordinary func
tion declaration are needed, and function max(int,int) needs to be
explicitly specialized, both the overloaded function declaration and
the declaration for the explicit template specialization can be pro
vided. For example,
template<class T> T max(T a, T b) { return a>b?a:b; }
template<> int max<>(int a, int b) { /* ... */ }
void g(char x, int y)
{
max(x,y); // error: no exact match, and no conversions allowed
}
int max(int,int);
void f(char x, int y)
{
max(x,y); // max<int>(int(x),y)
}
--end note]