______________________________________________________________________
14 Templates [temp]
______________________________________________________________________
1 A class template defines the layout and operations for an unbounded
set of related types. For example, a single class template List might
provide a common definition for list of int, list of float, and list
of pointers to Shapes. A function template defines an unbounded set
of related functions. For example, a single function template sort()
might provide a common definition for sorting all the types defined by
the List class template.
2 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 must declare or define a
function or a class, define a static data member of a template class,
or define a template member of a class. A template-declaration is a
declaration. A template-declaration is a definition (also) if its
declaration defines a function, a class, or a static data member of a
template class. There must be exactly one definition for each tem
plate in a program. There can be many declarations. Multiple defini
tions of a template in a single compilation unit is a required diag
nostic. Multiple definitions of a template in different compilation
units is a nonrequired diagnostic.
3 The names of a template obey the usual scope and access control rules.
A template-declaration can appear only as a global declaration, as a
member of a namespace, as a member of a class, or as a member of a
class template. A member template shall not be virtual. A destructor
shall not be a template. A local class shall not have a member tem
plate.
4 A template shall not have C linkage. If the linkage of a template is
something other than C or C++, the behavior is implementation-defined.
5 A vector class template might be declared like this:
template<class T> class vector {
T* v;
int sz;
public:
vector(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, vector is a parameterized type with T as its parameter.
A class template definition specifies how individual classes can be
constructed much as a class definition specifies how individual
objects can be constructed.
6 A member template can be defined within its class or separately. For
example:
template<class T> class string {
public:
template<class T2> compare(const T2&);
template<class T2> string(const string<T2>& s) { /* ... */ }
// ...
};
template<class T> template<class T2> string<T>::compare(const T2& s)
{
// ...
}
14.1 Template names [temp.names]
1 A template can be referred to by a template-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
2 A template-id that names a template class is a class-name (_class_).
3 A template-id that names a defined template class can be used exactly
like the names of other defined classes. For example:
vector<int> v(10);
vector<int>* p = &v;
Template-ids that name functions are discussed in _temp.fct_.
4 A template-id that names a template class that has been declared but
not defined can be used exactly like the names of other declared but
undefined classes. For example:
template<class T> class X; // X is a class template
X<int>* p; // ok: pointer to declared class X<int>
X<int> x; // error: object of undefined class X<int>
5 The name of a template followed by a < is always taken as the begin
ning of a template-id and never as a name followed by the less-than
operator. Similarly, the first non-nested > is taken as the end of
the template-argument-list rather than a greater-than operator. For
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
+------- BEGIN BOX 1 -------+
Should we bless a hack allowing Y<X<1>>? (yes, that would help users)
+------- END BOX 1 -------+
6 The name of a class template shall not be declared to refer to any
other template, class, function, object, namespace, value, or type in
the same scope. Unless explicitly specified to have internal linkage,
a template in namespace scope has externaml linkage (_basic.link_). A
global template name shall be unique in a program.
14.2 Name resolution [temp.res]
1 A name used in a template is assumed not to name a type unless it has
been explicitly declared to refer to a type in the context enclosing
the template declaration or in the template itself before its use.
For example:
// no B declared here
class X;
template<class T> class Y {
class Z; // forward declaration of member class
typedef T::A; // A is a type name
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
T::A* a5; // declare pointer to T's A
B* a6; // B is not a type name:
// multiply B by a6
}
};
2 The construct:
type-name-declaration:
typedef qualified-name ;
is a declaration that states that qualified-name must name a type, but
gives no clue to what that type might be. The qualified-name must
include a qualifier containing a template parameter or a template
class name.
3 Knowing which names are type names allows the syntax of every template
declaration to be checked. Syntax errors in a template declaration
can therefore be diagnosed at the point of the declaration exactly as
errors for non-template constructs. Other errors, such as type errors
involving template parameters, cannot be diagnosed until later; such
errors shall be diagnosed at the point of instantiation or at the
point where member functions are generated (_temp.inst_). Errors that
can be diagnosed at the point of a template declaration, shall be
diagnosed there or later together with the dependent type errors. For
example:
template<class T> class X {
// ...
void f(T t, int i, char* p)
{
t = i; // typecheck at point of instantiation,
// or at function generation
p = i; // typecheck immediately at template declaration,
// at point of instantiation,
// or at function generation
}
};
+------- BEGIN BOX 2 -------+
There is a potentially serious problem with the rule that a name is a
non-type name unless it has been explicitly specified to be the name
of a type. In some contexts, there is no way of indicating that a
name is a type name before using it. For example:
template <class Predicate> class unary_negate
: unary_function<Predicate::argument_type, int>, // syntax error!
restrictor<Predicate>
{
// ...
};
There are two alternative solutions: (1) Allow the compiler to assume
that a qualified name is the name of a type in ``such contexts,'' thus
making the example above well-formed as written. (2) Introduce a key
word to allow the programmer to state that a name is a type name as
part of using that name. For example:
template <class Predicate> class unary_negate
: unary_function<typename Predicate::argument_type, int>,
restrictor<Predicate>
{
// ...
};
Solution (2) would replace the type-name-declaration construct.
+------- END BOX 2 -------+
4 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 from the scope of the template definition.
--Names dependent on a template-argument (_temp.arg_) from the scope
of a template instantiation.
5 For example:
#include<iostream.h>
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';
}
// ...
};
When looking for the declaration of a name used in a template defini
tion the usual lookup rules (_class.scope0_) are first applied. Thus,
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.h. However, not every declaration can be found
this way; the resolution of some names must be postponed until the
actual template-argument is known. For example, the operator<< needed
to print p[i] cannot be known until it is known what type T is
(_temp.dep_).
14.2.1 Locally declared names [temp.local]
1 Within the scope of a template or a specialization of a template the
name of the template is equivalent to the name of the template quali
fied by the template-parameter. Thus, the constructor for Set can be
referred to as Set() or Set<T>(). Other specializations (_temp.spec_)
of the class can be referred to by explicitly qualifying the template
name with appropriate template-arguments. For example:
template<class T> class X {
X* p; // meaning X<T>
X<T>* p2;
X<int>* p3;
};
template<class T> class Y;
class Y<int> {
Y* p; // meaning Y<int>
};
See _temp.param_ for the scope of template-parameters.
2 A template type-parameter can be used in an elaborated-type-specifier.
For example:
template<class T> class A {
friend class T;
class T* p;
class T; // error: redeclaration of template parameter T
// (a name declaration, not an elaboration)
// ...
}
3 However, a specialization of a template for which a type-parameter
used this way is not in agreement with the elaborated-type-specifier
(_dcl.type_) is ill-formed. For example:
class C { /* ... */ };
struct S { /* ... */ };
union U { /* ... */ };
enum E { /* ... */ };
A<C> ac; // ok
A<S> as; // ok
A<U> au; // error: parameter T elaborated as a class,
// but the argument supplied for T is a union
A<int> ai; // error: parameter T elaborated as a class,
// but the argument supplied for T is an int
A<E> ae; // error: parameter T elaborated as a class,
// but the argument supplied for T is an enumeration
14.2.2 Names from the template's enclosing scope [temp.encl]
1 If a name used in a template isn't defined in the template definition
itself, names declared in the scope enclosing the template are consid
ered. If the name used is found there, the name used refers to the
name in the enclosing context. For 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)
In this, a template definition behaves exactly like other definitions.
For example:
void g(double);
void h();
class ZZ {
public:
void f() {
g(1); // calls g(double)
h++; // error: cannot increment function
}
};
void g(int); // not in scope at the point of class ZZ
// definition, not considered for the call g(1)
14.2.3 Dependent names [temp.dep]
1 Some names used in a template are neither known at the point of the
template definition nor declared within the template definition. Such
names shall depend on a template-argument and shall be in scope at the
point of the template instantiation (_temp.inst_). For example:
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.
2 A function call depends on a template-argument if the call would have
a different resolution or no resolution if the actual template type
were missing from the program. Examples of calls that depend on an
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(Vector<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 is a 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
depended 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
}
+------- BEGIN BOX 3 -------+
It has been suggested that a full list of cases would be a better def
inition than the general rule we decided on in San Jose. I strongly
prefer a general rule, but we should be open to clarifications if peo
ple feel the need for them.
+------- END BOX 3 -------+
3 This ill-formed template instantiation uses a function that does not
depend on a template-arguments:
template<class T> class Z {
public:
void f() {
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-parameter ``Horse''
}
The call x.f() gives raise to the specialization:
Z<Horse>::f() { g(1); }
The call g(1) would call g(int), but since that call in no way depends
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.
4 On the other hand:
void h(const Z<int>& y)
{
y.f(); // fine: g(int) called by g(1) depends
// on template-parameter ``int''
}
Here, the call y.f() gives raise to the specialization:
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.
5 A name from a base class can hide the name of a template-parameter.
For example:
struct A {
struct B { /* ... */ };
int a;
};
template<class B, class a> struct X : A {
B b; // A's B
a b; // error: A's a isn't a type name
};
However, a name from a template argument cannot hide a name from the
template or its enclosing scopes. For example:
int a;
template<class T> struct Y : T {
struct B { /* ... */ };
B b; // The B defined in Y
void f(int i) { a = i; } // the global a;
};
Y<A> ya;
The members A::B and A::a of the template argument A do not affect the
binding of names in Y<A>.
6 A name of a member can hide the name of a template-parameter. For
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
}
14.2.4 Non-local names declared within a template [temp.inject]
1 Names that are not template members can be declared within a template
class or function. However, such declarations must match declarations
in scope at the point of their declaration or instantiation. For
example:
void f();
// no Y, Z, or g here
template<class T> class X {
friend class Y; // error: No Y in scope
class Z * p; // error: No Z in scope
friend T operator+(const T&, const T&); // checking delayed
friend void f(); // ok
friend void f(T); // checking delayed
};
class C {
friend C operator+(const C&, const C&);
};
void f(C);
class D { };
void g()
{
X<C> c; // ok: operator+(const C&, const C&) and f(C) in scope
X<D> d; // error: no operator+(const D&, const D&) or f(D)
}
+------- BEGIN BOX 4 -------+
In #94-0116/N503 Barton and Nackman argue strongly that some form of
name injection is essential so that this rule should be relaxed. See
also Spicer Issue 2.23.
+------- END BOX 4 -------+
14.3 Template instantiation [temp.inst]
1 A class generated from a class template is called a generated class.
A function generated from a function template is called a generated
function. A static data member generated from a static data member
template is called a generated static data member. A class defined
with a template-id as its name is called an explicitly specialized
class. A function defined with a template-id as its name is called an
explicitly specialized function. A static data member defined with a
template-id as its name is called an explicitly specialized static
data member. A specialization is a class, function, or static data
member that is either generated or explicitly specialized.
2 The act of generating a class, function, or static data member from a
template is commonly referred to as template instantiation.
14.3.1 Making template definitions available [temp.avail]
1 A template can be instantiated for a set of template arguments only if
the definition of the template is available.
+------- BEGIN BOX 5 -------+
The definition of ``available'' has yet to be determined. Two main
lines of approach are being considered: (1) Make translation units
containing template definitions available to the compilation system in
some extra-linguistic way; see §4 of #94-0024/N0413. (2) Make tem
plate definitions available through some form of explicit template
directives.
2 Here is the template directive variant proposed at the Waterloo meet
ing:
3 A template that has been used in a way that requires a specialization
of its definition may be explicitly specialized (_temp.spec_) or
explicitly instantiated (_temp.explicit_) within the current
translation unit, otherwise the specialization will be implicitly gen
erated if the definition has either been previously made available
through a template-directive or has been previously defined in the
current translation unit, else the template shall be explicitly
instantiated within the program.
4 The syntax for a template directive is:
template-directive:
template string-literal ;
A template-directive nominates a translation unit containing defini
tions of templates that have been declared in the current translation
unit. There shall be an implementation- defined mapping between the
string-literal and an external source file name that is used to pro
duce the nominated translation unit. The nominated translation unit
is produced using the same environment as for the current translation
unit. Names declared in the current translation unit are not visible
within the nominated translation unit. Names declared within the nom
inated translation unit do not become visible within the current
translation unit. After a template-directive has been processed, the
template definitions within the nominated translation unit are avail
able for use in instantiation of the declared templates if required.
Definitions of objects or functions with external linkage within the
nominated translation unit shall be well-formed but shall otherwise be
treated as declarations only (i.e., no storage will be allocated and
no code will be generated). A template-directive shall not appear in
class scope or local scope. The treatment of definitions of objects
or functions with internal linkage will be revisited when linkage
issues are resolved.
5 In order to explicitly instantiate the specialization, the definition
shall either be made available through a template-directive or shall
have been previously defined in the current translation unit. For
explicit instantiation of a class, the definition of all members shall
be made available.
+------- END BOX 5 -------+
14.3.2 Point of instantiation [temp.point]
1 The point of instantiation of a template is the point where names
dependent on the template-argument are bound. That point is immedi
ately before the declaration in the nearest enclosing global or names
pace scope containing the first use of the template requiring its def
inition. This implies that names used in a template definition 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 mem
bers. For example:
// void g(int); not declared here
template<class T> class Y {
public:
void f() { g(1); }
};
void k(const Y<int>& h)
{
void g(int);
h.f(); // error: g(int) called by g(1) not found
// local g() not considered
}
class C {
void g(int);
void m(const Y<int>& h)
{
h.f(); // error: g(int) called by g(1) not found
// C::g() not considered
}
};
namespace N {
void g(int);
void n(const Y<int>& h)
{
h.f(); // N::g(int) called by g(1)
}
}
+------- BEGIN BOX 6 -------+
This was discussed, but not voted on in Waterloo. The previous ver
sion was plain wrong.
+------- END BOX 6 -------+
2 Each compilation unit in which the definition of a template is used
has a point of instantiation for the template. If this causes names
used in the template definition to bind to different names in differ
ent compilations, the one-definition rule has been violated and any
use of the template is ill-formed. Such violation does not require a
diagnostic.
3 A template can be either explicitly instantiated for a given argument
list or be implicitly instantiated. A template that has been used in
a way that require a specialization of its definition will have the
specialization implicitly generated unless it has either been explic
itly instantiated (_temp.explicit_) or explicitly specialized
(_temp.spec_). A specialization will not be implicitly generated
unless the definition of a template specialization is required. For
example:
template<class T> class Z {
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 instantiated. An implementation shall not instan
tiate a function or a class that does not require instantiation. How
ever, virtual functions can be instantiated for implementation pur
poses.
4 If a virtual function is instantiated, its point of instantiation is
immediately following the point of instantiation for its class.
+------- BEGIN BOX 7 -------+
There has been no vote on the point of instantiation for a virtual
function.
+------- END BOX 7 -------+
5 The 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.
namespace N {
template<class T> class List {
public:
T* get();
// ...
};
}
template<class K, class V> class Map {
List<V> lt;
V get(K);
// ...
};
void g(Map<char*,int>& m)
{
int i = m.get("Nicholas");
// ...
}
This allows instantiation of a used template to be done before instan
tiation of its user.
6 The rules specifying where definitions are required (above) prevent
mutually dependent definitions from causing mutually recursive instan
tiations.
7 Implicitly generated template classes, functions, and static data mem
bers are placed in the namespace where the template was defined. For
example, a call of lt.get() from Map<char*,int>::get() would place
List<int>::get() in N rather than in the global space.
+------- BEGIN BOX 8 -------+
There has been no vote on the point of instantiation for an indirectly
generated template specialization. This rule gets interesting only if
template instantiation can cause name injection (_temp.inject_).
+------- END BOX 8 -------+
8 If a template for which a definition is in scope is used in a way that
involves overload resolution or conversion to a base class, the defi
nition of a template specialization is required. For 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>*
}
9 If an instantiation of a class template is required and the template
is declared but not defined, the program is ill-formed. For example:
template<class T> class X;
A<char> ch; // error: definition of X required
10Recursive instantiation is possible. For example:
template<int i> int fac() { return i>1 ? i*fac<i-1>() : 1; }
int fac<0>() { return 1; }
int f()
{
return fac<17>();
}
11There shall be an implementation quantity that specifies the limit on
the depth of recursive instantiations.
+------- BEGIN BOX 9 -------+
Put limit with deafult 17 in Annex B.
+------- END BOX 9 -------+
12The result of an infinite recursion in instantiation is undefined. In
particular, an implementation is allowed to report an infinite recur
sion as being ill-formed. For example:
template<class T> class X {
X<T>* p; // ok
X<T*> a; // instantiation of X<T> requires
// the instantiation of X<T*> which requires
// the instantiation of X<T**> which ...
};
13No 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.
14An explicit specialization or explicit instantiation of a template
must be in the namespace in which the template was defined. For exam
ple:
namespace N {
template<class T> class X { /* ... */ };
template<class T> class Y { /* ... */ };
template<class T> class Z {
void f(int i) { g(i); }
// ...
};
class X<int> { /* ... */ }; // ok: specialization
// in same namespace
}
template class Y<int>; // error: explicit instantiation
// in different namespace
template class N::Y<char*>; // ok: explicit instantiation
// in same namespace
class N::Y<char*> /* ... */ }; // ok: specialization
// in same namespace
15A member function of an explicitly specialized class cannot be implic
itly generated from the general template. Instead, the member func
tion must itself be explicitly specialized. For example:
template<class T> struct A {
void f() { /* ... */ }
};
struct A<int> {
void f();
};
void h()
{
A<int> a;
a.f(); // A<int>::f must be defined somewhere
}
void A<int>::f() { /* ... */ };
Thus, an explicit specialization of a class implies the declaration of
specializations of all of its members. The definition of each such
specialized member which is used must be provided in some compilation
unit.
14.3.3 Instantiation of operator->
1 If a template class has an operator->, that operator-> can have a
return type that cannot be dereferenced by -> as long as that opera
tor-> is neither invoked, nor has its address taken, isn't virtual,
nor is explicitly instantiated. For example:
template<class T> class Ptr {
// ...
T* operator->();
};
Ptr<int> pi; // ok
Ptr<Rec> pr; // ok
void f()
{
pi->m = 7; // error: Ptr<int>::operator->() returns a type
// that cannot be dereference by ->
pr->m = 7; // ok if Rec has an accessible member m
// of suitable type
}
14.4 Explicit instantiation [temp.explicit]
1 A class or function specialization can be explicitly instantiated from
its template.
2 The syntax for explicit instantiation is:
explicit-instantiation:
template inst ;
inst:
class-key template-id
type-specifier-seq template-id ( parameter-declaration-clause )
+------- BEGIN BOX 10 -------+
Syntax WG: please check this grammar. It ought to allow any declara
tion that is not a definition of a class or function with a template-
id as the name being declared.
+------- END BOX 10 -------+
For example:
template class vector<char>;
template void sort<char>(vector<char>&);
3 A declaration of the template must be in scope and the definition of
the template must be available at the point of explicit instantiation.
+------- BEGIN BOX 11 -------+
Exactly what ``must be available'' means depends on the compilation
model we adopt for templates.
+------- END BOX 11 -------+
4 A trailing template-argument can be left unspecified in an explicit
instantiation or explicit specialization of a template function pro
vided it can be deduced from the function argument type. For example:
// instantiate sort(vector<int>&):
// deduce template-argument:
template void sort<>(vector<int>&);
5 The explicit instantiation of a class implies the instantiation of all
of its members not previously explicitly specialized in the compila
tion unit containing the explicit instantiation.
14.5 Template specialization [temp.spec]
1 A specialized template function, template class, or static member of a
template can be declared by a declaration where the declared name is a
template-id, that is:
specialization:
declaration
+------- BEGIN BOX 12 -------+
Syntax WG: please check this grammar. Should the fact that a tem
plate-id must be the name declared be made explicit in the grammar?
+------- END BOX 12 -------+
For example:
template<class T> class stream;
class stream<char> { /* ... */ };
template<class T> void sort(vector<T>& v) { /* ... */ }
void sort<char*>(vector<char*>&) ;
Given these declarations, stream<char> will be used as the definition
of streams of chars; other streams will be handled by template classes
generated from the class template. Similarly, sort<char*> will be
used as the sort function for arguments of type vector<char*>; other
vector types will be sorted by functions generated from the template.
2 A declaration of the template being specialized must be in scope at
the point of declaration of a specialization. For example:
class X<int> { /* ... */ }; // error: X not a template
template<class T> class X { /* ... */ };
class X<char*> { /* ... */ }; // fine: X is a template
3 If a template is explicitly specialized then that specialization must
be declared before the first use of that specialization in every
translation unit in which it is used. For example:
template<class T> void sort(vector<T>& v) { /* ... */ }
void f(vector<String>& v)
{
sort(v); // use general template
// sort(vector<T>&), T is String
}
void sort<String>(vector<String>& v); // error: specialize after use
void sort<>(vector<char*>& v); // fine sort<char*> not yet used
If a function or class template has been explicitly specialized for a
template-argument list no specialization will be implicitly generated
for that template-argument list.
4 Note that a function with the same name as a template and a type that
exactly matches that of a template is not a specialization
(_temp.over.spec_).
14.6 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
typedef identifieropt
typedef identifieropt = type-name
template < template-parameter-list > class identifieropt
template < template-parameter-list > class identifieropt = template-name
For example:
template<class T> myarray { /* ... */ };
template<class K, class V, template<class T> class C = myarray>
class Map {
C<K> key;
C<V> value;
// ...
};
+------- BEGIN BOX 13 -------+
This grammar leaves out namespace template-parameters. See §2 of ANSI
X3J16/94-0026, ISO WG21/N0413.
+------- END BOX 13 -------+
+------- BEGIN BOX 14 -------+
Should this grammar be modified to accept struct as well as class for
template template-parameters?
+------- END BOX 14 -------+
2 Default arguments shall not be specified in a declaration or a defini
tion of a specialization.
3 A type-parameter defines its identifier to be a type-name in the scope
of the template declaration. A type-parameter shall not be redeclared
within its scope (including nested scopes). A non-type template-
parameter shall not be assigned to or in any other way have its value
changed. For example:
template<class T, int i> class Y {
int T; // error: template-parameter redefined
void f() {
char T; // error: template-parameter redefined
i++; // error: change of template-argument value
}
};
template<class X> class X; // error: template-parameter redefined
4 A template-parameter that could be interpreted as either an parameter-
declaration or a type-parameter (because its identifier is the name of
an already existing class) is taken as a type-parameter. A template-
parameter hides a variable, type, constant, etc. of the same name in
the enclosing scope. For example:
class T { /* ... */ };
int i;
template<class T, T i> void f(T t)
{
T t1 = i; // template-arguments T and i
::T t2 = ::i; // globals T and i
}
Here, the template f has a type-parameter called T, rather than an
unnamed non-type parameter of class T. There is no semantic differ
ence between class and typedef in a template-parameter.
5 There are no restrictions on what can be a template-argument type
beyond the constraints imposed by the set of argument types
(_temp.arg_). In particular, reference types and types containing cv-
qualifiers are allowed. A non-reference template-argument cannot have
its address taken. When a non-reference template-argument is used as
an initializer for a reference a temporary is always used. For exam
ple:
template<const X& x, int i> void f()
{
&x; // ok
&i; // error: address of non-reference template-argument
int& ri = i; // error: non-const reference bound to temporary
const int& cri = i; // ok: reference bound to temporary
}
6 A non-type template-parameter cannot be of floating type because only
integral constant expressions (_expr.const_) are considered as tem
plate-arguments for non-type template parameters and standard conver
sions are not applied to template-arguments. For example:
template<double d> class X; // error
template<double* pd> class X; // ok
template<double& rd> class X; // ok
7 A default template-argument is a type or a value specified after = in
a template-parameter. A default template-argument can be specified in
a template declaration or a template definition. A function template
shall not have default template-arguments. The set of default tem
plate-arguments available for use with a template declaration or defi
nition is obtained by merging the default arguments from the defini
tion (if in scope) and all declarations in scope in the same way
default function arguments are (_dcl.fct.default_). For example:
template<class T1, class T2 = int> class A;
template<class T1 = int, class T2> class A;
is equivalent to
template<class T1 = int, class T2 = int> class A;
If a template-parameter has a default argument all subsequent tem
plate-parameters must have a default argument supplied in the same or
previous declarations of the template. For example:
template<class T1 = int, class T2> class B; // error
A template-parameter shall not be given default arguments by two dif
ferent declarations in the same scope.
template<class T = int> class X;
template<class T = int> class X { /*... */ }; // error
The scope of a template-argument extends from its point of declaration
until the end of its template. In particular, a template-parameter
can be used in the declaration of subsequent template-parameters and
their default arguments. For example:
template<class T, T* p, class U = T> class X { /* ... */ };
template<class T> void f(T* p = new T);
A template-parameter cannot be used in preceding template-parameters
or their default arguments.
8 A template-parameter can be used in the specification of base classes.
For example:
template<class T> class X : public vector<T> { /* ... */ };
template<class T> class Y : public T { /* ... */ };
Note that 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.
14.7 Template arguments [temp.arg]
1 The types of the template-arguments specified in a template-id must
match the types specified for the template in its template-parameter-
list. For example, vectors as defined in _temp_ can be used like
this:
vector<int> v1(20);
vector<complex> v2(30);
typedef vector<complex> cvec; // make cvec a synonym
// for vector<complex>
cvec v3(40); // v2 and v3 are of the same type
v1[3] = 7;
v2[3] = v3.elem(4) = complex(7,8);
2 A non-type non-reference template-argument must be a constant-
expression, the address of an object or a non-overloaded function with
external linkage, or a non-overloaded pointer to member. The address
of an object or function must be expressed as &f, plain f, or &X::f
where f is the function or object name. In the case of &X::f, X must
be a (possibly qualified) name of a class and f the name of a static
member of X. A pointer to member must be expressed as &X::m where X
is a (possibly qualified) name of a class and m is the member name.
In particular, a string literal (_lex.string_) is not an acceptable
template-argument because a string literal is the address of an object
with static linkage. For 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
3 Similarly, addresses of array elements and non-static class members
are not acceptable as template-arguments. For example:
int a[10];
struct S { int m; static int s; } s;
X<&a[2],p> x3; // error: address of element
X<&s.m,p> x4; // error: address of member
X<&s.s,p> x5; // error: address of member
X<&S::s,p> x6; // ok: address of static member
4 Nor is a local type or an type with no linkage name an acceptable tem
plate-argument. For example:
void f()
{
struct S { /* ... */ };
X<S,p> x3; // error: local type used as template-argument
}
5 Similarly, a reference template-parameter cannot be be bound to a tem
porary:
template<const int& CRI) struct B { /* ... */ };
B<1> b2; // error: temporary required for template argument
int c = 1;
B<c> b1; // ok
6 A template has no special access rights to its template-argument
types. However, often a template doesn't need any. For example:
class Y {
private:
struct S { /* ... */ };
X<S> x; // most operations by X on S do not lead to errors
};
X<Y::S> y; // most operations by X on Y::S leads to errors
The template X can use Y::S without violating any access rules as long
as it uses only the access through a template-argument that does not
explicitly mention Y.
7 An argument for a template-parameter of reference type must be an
object or function with external linkage, or a static class member. A
temporary object is not an acceptable argument to a template-parameter
of reference type.
8 When default template-arguments are used, a template-argument list can
be empty. In that case the empty <> brackets must still be used. For
example:
template<class T = char> class String;
String<>* p; // ok: String<char>
String* q; // syntax error
The notion of ``array type decay'' does not apply to template-
parameters. For example:
template<int a[5]> struct S { /* ... */ };
int v[5];
int* p = v;
S<v> x; // fine
S<p> y; // error
14.8 Type equivalence [temp.type]
1 Two template-ids refer to the same class or function if their template
names are identical and their arguments have identical values. For
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.9 Function templates [temp.fct]
1 A function template specifies how individual functions can be con
structed. A family of sort functions, for example, might be declared
like this:
template<class T> void sort(vector<T>);
A function template specifies an unbounded set of (overloaded) func
tions. A function generated from a function template is called a tem
plate function, so is an explicit specialization of a function tem
plate. Template arguments can either be explicitly specified in a
call or be deduced from the function arguments.
14.9.1 Explicit template argument [temp.arg.explicit]
specification
1 Template arguments can be specified in a call by qualifying the tem
plate function name by the list of template-arguments exactly as tem
plate-arguments are specified in uses of a class template. For exam
ple:
void f(vector<complex>& cv, vector<int>& ci)
{
sort<complex>(cv); // sort(vector<complex>)
sort<int>(ci); // sort(vector<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)
}
Implicit conversions (_conv_) are accepted for a function argument for
which the parameter has been fixed by explicit specification of a tem
plate-argument. For example:
template<class T> void f(T);
class complex {
// ...
complex(double);
};
void g()
{
f<complex>(1); // ok, means f<complex>((complex(1))
}
14.9.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. For example,
void f(vector<complex>& cv, vector<int>& ci)
{
sort(cv); // call sort(vector<complex>)
sort(ci); // call sort(vector<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)
}
2 A template type argument T or a template non-type argument i can be
deduced from a function argument composed from these elements:
T
cv-list T
T*
T&
T[integer-constant]
class-template-name<T>
type(*)(T)
type T::*
T(*)()
type[i]
class-template-name<i>
where the T in argument list form
type (*)(T)
includes argument lists with more than one argument where at least one
argument contains a T. Also, these forms can be used in the same way
as T is for further composition of types. For example,
X<int>(*)(v[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 v[6].
3 In addition, a template-parameter can be deduced from a function or
pointer to member function argument if at most one of a set of over
loaded functions provides a unique match. For example:
template<class T> void f(void(*)(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
}
Template arguments shall not be deduced from function arguments
involving other constructs.
4
+------- BEGIN BOX 15 -------+
Can a template template-parameter be deduced? and if so how? Spicer
issue 3.19.
+------- END BOX 15 -------+
5 Template arguments of an explicit instantiation or explicit special
ization are deduced (_temp.explicit_, _temp.spec_) according to these
rules specified for deducing function arguments.
6 Note that a major array bound is not part of a function parameter type
so it can't be deduced from an argument:
template<int i> void f1(int a[10][i]);
template<int i> void f2(int a[i][10]);
void g(int v[10][10])
{
f1(v); // ok: i deduced to be 10
f1<10>(v); // ok
f2(v); // error: cannot deduce template-argument i
f2<10>(v); // ok
}
7 Nontype parameters shall not be used in expressions in the function
declaration. The type of the function template-parameter must match
the type of the template-argument exactly. For example:
template<char c> class A { /* ... */ };
template<int i> void f(A<i>); // error: conversion not allowed
template<int i> void f(A<i+1>); // error: expression not allowed
8 Every template-parameter specified in the template-parameter-list must
be either explicitly specified or deduced from a function argument.
If function template-arguments are specified in a call they are speci
fied in declaration order. Trailing arguments can be left out of a
list of explicit template-arguments. For 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
}
9 A template-parameter cannot be deduced from a default function argu
ment. For example:
template <class T> void f(T = 5, T = 7);
void g()
{
f(1); // fine: call f<int>(1,7)
f(); // error: cannot deduce T
f<int>(); // fine: call f<int>(5,7)
}
10If a template parameter can be deduced from more than one function
argument the deduced template parameter must the same in each case.
For example:
template<class T> void f(T x, T y) { /* ... */ }
struct A { /* ... */ };
struct B : A { /* ... */ };
int g(A a, B b)
{
f(a,a); // ok: T is A
f(b,b); // ok: T is B
f(a,b); // error T could be A or B
f(b,a); // error: T could be A or B
}
14.9.3 Overload resolution [temp.over]
1 A template function can be overloaded either by (other) functions of
its name or by (other) template functions of that same name. Over
loading resolution for template functions and other functions of the
same name is done in the following three steps:
1)Look for an exact match (_over.match_) on functions; if found, call
it.
2)Look for a function template from which a function that can be
called with an exact match can be generated; if found, call it.
3)Look for match with conversions. For arguments to ordinary func
tions and for arguments to a template function that corresponds to
parameters whose type does not depend on a deduced template-
parameter, the ordinary best match rules apply. For template func
tions, only the following conversions listed below applies. After
the best matches are found for individual arguments, the intersec
tion rule (_over.match.args_) is used to look for a best match; if
found, call it.
+------- BEGIN BOX 16 -------+
Rephrase to match Clause 13.
+------- END BOX 16 -------+
2 For arguments that correspond to parameters whose type depends on a
deduced template parameter, the following conversions are allowed:
--For a parameter of the form B<params>, where params is a template
parameter list containing one or more deduced parameters, an argu
ment of type ``class derived from B<params>'' can be converted to
B<params>. Additionally, for a parameter of the form B<params>*,
an argument of type ``pointer to class derived from B<params>''
can be converted to B<params>*. Similarly for references. Also,
for a parameter of the form T an argument of type ``T B::* where B
is a base of D<params>'' can be converted to T D<params>::*.
--A pointer (reference) can be converted to a more qualified pointer
(reference) type, according to the rules in _conv.ptr_
(_conv.ref_).
--``array of T'' to ``pointer to T.''
--``function ...'' to ``pointer to function to ... .''
+------- BEGIN BOX 17 -------+
The pointer to member case added editorially.
+------- END BOX 17 -------+
3 If no match is found the call is ill-formed. In each case, if there
is more than one alternative in the first step that finds a match, the
call is ambiguous and is ill-formed.
4 A match on a template (step (2)) implies that a specific template
function with parameters that exactly match the types of the arguments
will be generated (_temp.inst_). Not even trivial conversions
(_over.match_) will be applied in this case.
+------- BEGIN BOX 18 -------+
This maybe too strict. See the proposal for a more general overloaded
mechanism in N0407/94-0020 (issue 3.9).
+------- END BOX 18 -------+
5 The same process is used for type matching for pointers to functions
(_over.over_) and pointers to members.
6 Here is an example:
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)
}
7 For example, 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.
8 Here is an example involving conversions on a function argument
involved in template-parameter 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 )
}
9 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))
}
10The template definition is needed to generate specializations of a
template. However, only a function template declaration is needed to
call a specialization. For example,
template<class T> void f(T); // declaration
void g()
{
f("Annemarie"); // call of f<char*>
}
The call of f is well formed because of the the declaration of f, and
the program will be ill-formed unless a definition of f is present in
some translations unit.
11In case a call has explicitly qualified template-arguments and
requires overload resolution, the explicit qualification is used first
to determine the set of overloaded functions to be considered and
overload resolution then takes place for the remaining arguments. For
example:
template<class X, class Y> void f(X,Y*); // #1
template<class X, class Y> void f(X*,Y); // #2
void g(char* pc, int* pi)
{
f(0,0); // error: ambiguous: f<int,int>(int,int*)
// or f<int,int>(int*,int) ?
f<char*>(pc,pi); // #1: f<char*,int>(char*,int*)
f<char>(pc,pi); // #2: f<char,int*>(char*,int*)
}
14.9.4 Overloading and specialization [temp.over.spec]
1 A template function can be overloaded by a function with the same type
as a potentially generated function. For 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; }
Such an overloaded function is a specialization but not an explicit
specialization. The declaration simply guides the overload resolu
tion. This implies that a definition of max(int,int) and min(int,int)
will be implicitly generated from the templates. If such implicit
instantiation is not wanted, the explicit specialization syntax should
be used instead:
template<class T> T max(T a, T b) { return a>b?a:b; }
int max<int>(int a, int b);
2 Defining a function with the same type as a template specialization
that is called is ill-formed. For 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()
}
If the two definitions of max() are not in the same translation unit
the diagnostic is not required. If a separate definition of a func
tion max(int,int) is needed, the specialization syntax can be used.
If the conversions enabled by an ordinary declaration are also needed,
both can be used. For example:
template<class T> T max(T a, T b) { return a>b?a:b; }
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)
}
14.10 Member function templates [temp.mem.func]
1 A member function of a template class is implicitly a template func
tion with the template-parameters of its class as its template-
parameters. For example,
template<class T> class vector {
T* v;
int sz;
public:
vector(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& vector<T>::operator[](int i)
{
if (i<0 || sz<=i) error("vector: range error");
return v[i];
}
2 The template-argument for vector<T>::operator[]() will be determined
by the vector to which the subscripting operation is applied.
vector<int> v1(20);
vector<complex> v2(30);
v1[3] = 7; // vector<int>::operator[]()
v2[3] = complex(7,8); // vector<complex>::operator[]()
14.11 Friends [temp.friend]
1 A friend function of a template can be a template function or a non-
template function. For 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.
template<class T> task<T>* preempt(task<T>* t) { /* ... */ }
2 A friend template shall not be defined within a class. For example:
class A {
friend template<class T> B; // ok
friend template<class T> f(T); // ok
friend template<class T> BB { /* ... /* }; // error
friend template<class T> ff(T){ /* ... /* } // error
};
14.12 Static members and variables [temp.static]
1 Each template class or function generated from a template has its own
copies of any static variables or members. For example,
template<class T> class X {
static T s;
// ...
};
X<int> aa;
X<char*> bb;
Here X<int> has a static member s of type int and X<char*> has a
static member s of type char*.
2 Static class member templates are defined similarly to member function
templates. For example,
template<class T> T X<T>::s = 0;
int X<int>::s = 3;
3 Similarly,
template<class T> f(T* p)
{
static T s;
// ...
};
void g(int a, char* b)
{
f(&a);
f(&b);
}
Here f(int*) has a static member s of type int and f(char**) has a
static member s of type char*.