______________________________________________________________________ 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 shall 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 shall 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. +------- BEGIN BOX 1 -------+ This - and all other requirements for unique definitions of templates in this clause - will have to be rephrased to take the ODR into account when the ODR is completely defined. +------- END BOX 1 -------+ 3 The name of a template obeys 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 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 external linkage (_basic.link_). A global template name shall be unique in a program. 7 In a template-argument, an ambiguity between a type-id and an expres sion is resolved to a type-id. For example: template<class T> void f(); template<int I> void f(); void g() { f<int()>(); // ``int()'' is a type-id: call the first f() } 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 is qualified by the keyword typename. For 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 } }; 2 In a template, any use of a qualified-name where the qualifier depends on a template-parameter can 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 > 3 If a specialization of that template is generated for a template- argument such that the qualified-name does not denote a type, the spe cialization is ill-formed. is a declaration that states that quali fied-name names a type, but gives no clue to what that type might be. The qualified-name shall include a qualifier containing a template parameter or a template class name. 4 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 } }; No diagnostics shall be issued for a template definition for which a valid specialization can be generated. 5 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. 6 For 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'; } // ... }; 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 even though the name operator<< is known within the definition of sum() an a declara tion of it can be found in <iostream>, the actual declaration of oper ator<< needed to print p[i] cannot be known until it is known what type T is (_temp.dep_). 7 If a name can be bound at the point of the template definition and it is not a function called in a way that depends on a template-parameter (as defined in _temp.dep_), it will be bound at the template defini tion point and the binding is not affected by later declarations. For example: void f(int); template<class T> void g(T t) { f(1); // f(int) f(T(1)); // dependent f(t); // dependent } void f(char); void h() { f('a'); // will cause two calls of f(int) followed // by a call of f(char) } 14.2.1 Locally declared names [temp.local] 1 Within the scope of a class template or a specialization of a template the name of the template is equivalent to the name of the template qualified 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 a type, template, or named constant mentioned in the template-argument were missing from the pro gram. 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 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 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 } 3 This ill-formed template instantiation uses a function that does not depend on a template-argument: 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; 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 }; 6 However, a name from a template-argument cannot hide a name declared within a template, a template-parameter, or a name from the template's 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* 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>. 7 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. When a template is specialized, the names declared in it are declared as if the specialization had been explicitly declared at its point of instantiation. If a template is first spe cialized as the result of use within a block or class, names declared within the template shall be used only after the template use that caused the specialization. For 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 // Here is the point of instantiation for X<C> 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 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 Template linkage [temp.linkage] 1 A function template has external linkage, as does a static member of a class template. Every function template shall have the same defini tion in every translation unit in which it appears. 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) } } 2 Names from both the namespace of the template itself and of the names pace containing the point of instantiation of a specialization are used to resolve names for the specialization. Overload resolution is used to chose between functions with the same name in these two names paces. For 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); // instantiation point for NN:f(int) and NN::f(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. } } If a name is found in both namespaces and overload resolution cannot resolve a use, the program is ill-formed. 3 Each compilation unit in which the definition of a template is used in a way that require definition of a specialization has a point of instantiation for the template. If this causes names used in the tem plate definition to bind to different names in different compilations, the one-definition rule has been violated and any use of the template is ill-formed. Such violation does not require a diagnostic. 4 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. 5 If a virtual function is instantiated, its point of instantiation is immediately following the point of instantiation for its class. 6 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. 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 2 -------+ Name injection from an implicitly generated template function special ization are under debate. That is, it might be banned. +------- END BOX 2 -------+ 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; X<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. 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 shall be in the namespace in which the template was defined. For example: 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<double> { /* ... */ }; // ok: specialization // in same namespace 15A member function of an explicitly specialized class shall not be implicitly generated from the general template. Instead, the member function shall 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 shall be provided in some translation 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 3 -------+ 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 3 -------+ For example: template class vector<char>; template void sort<char>(vector<char>&); 3 A declaration of the template shall be in scope at the point of explicit instantiation. 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 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 shall 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 shall 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 typename identifieropt typename identifieropt = type-id template < template-parameter-list > class identifieropt template < template-parameter-list > class identifieropt = template-name 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; // ... }; 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 typename 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 shall not be of floating type. 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, value, or template specified after = in a template-parameter. A default template-argument can be specified in a template declaration or a 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 unit. 8 If a template-parameter has a default argument, all subsequent tem plate-parameters shall have a default argument supplied. For example: template<class T1 = int, class T2> class B; // error 9 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. 10A 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 shall 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 shall be a constant- expression of non-floating type, the address of an object or a func tion 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 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 (dot operator used) 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 bound to a tempo rary: template<const int& CRI) struct B { /* ... */ }; B<1> b2; // error: temporary required for template argument int c = 1; B<c> b1; // ok 6 An argument to a template-parameter of pointer to function type shall have exactly the type specified by the template parameter. This allows selection from a set of overloaded functions. For example: void f(char); void f(int); template<void (*pf)(int)> struct A { /* ... */ }; A<&f> a; // selects f(int) 7 A template has no special access rights to its template-argument types. A template-argument shall be accessible at the point where it is used as a template-argument. For 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 8 In addition to the rules for non-reference template-arguments, an argument for a template-parameter of reference type shall not be a constant-expression. In particular, a temporary object is not an acceptable argument to a template-parameter of reference type. 9 When default template-arguments are used, a template-argument list can be empty. In that case the empty <> brackets shall 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 in the same scope and their template-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 tem plate-arguments. For example: template<class T> void f(T); class complex { // ... complex(double); }; void g() { f<complex>(1); // ok, means f<complex>((complex(1)) } +------- BEGIN BOX 4 -------+ There is a problem with the explicit qualification of member template functions. Consider: class X { public: template<size_t> X* malloc(); // ... }; void f(X* p) { X* pi = p->malloc<200>(); } There is no way of knowing that X::malloc is a template name until after type checking. Consequently, this example cannot be syntax analysed. One solution is ``then do not do that.'' Another is to provide some form of explicit qualification. For example: X* pi = p-> templatename malloc<200>(); or X* pi = p-> template malloc<200>(); The latter, use of the keyword template, in general clashes with the use of template for explicit instantiation (_temp.explicit_). +------- END BOX 4 -------+ 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(*)() T(*)(T) type[i] class-template-name<i> where (T) includes argument lists with more than one argument where at least one argument contains a T, and where () includes argument lists with arguments that do not contain a T. Also, these forms can be used in the same way as T is for further composition of types. For exam ple, 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]. 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 constructs other than the ones specified in here (_temp.deduct_). +------- BEGIN BOX 5 -------+ Can a template template-parameter be deduced? and if so how? Spicer issue 3.19. +------- END BOX 5 -------+ 4 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. 5 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][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 } 6 Nontype parameters shall not be used in expressions in the function declaration. The type of the function template-parameter shall 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 7 Every template-parameter specified in the template-parameter-list shall be either explicitly specified or deduced from a function argu ment. If function template-arguments are specified in a call they are specified 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 } 8 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) } 9 If a template parameter can be deduced from more than one function argument the deduced template parameter shall 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 functions 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 6 -------+ Rephrase to match Clause 13. +------- END BOX 6 -------+ 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.1) --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 ... .'' 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 7 -------+ This maybe too strict. See the proposal for a more general overloaded mechanism in N0407/94-0020 (issue 3.9). +------- END BOX 7 -------+ 5 The same process is used for type matching for pointers to functions (_over.over_) and pointers to members. _________________________ 1) It would be nice if an argument of type ``T B::* where B is a base of D<params>'' could be converted to T D<params>::*. Unfortunately this would require an unbounded search of possible instantiations. 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) } 3 An explicit specialization of a function template shall be inline or static only if it is explicitly declared to be, and independently of whether its function template is. For example: template<class T> void f(T) { /* ... */ } template<class T> inline T g(T) { /* ... */ } inline void f<>(int) { /* ... */ } // ok: inline int g<>(int) { /* ... */ } // ok: not inline 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 friend template<class T> f(T); // ok friend template<class T> BB { /* ... /* }; // error friend template<class T> ff(T){ /* ... /* } // error }; Note that a friend declaration can add a name to an enclosing scope (_temp.inject_). +------- BEGIN BOX 8 -------+ The syntax above isn't allowed by the grammar. The grammar allows only: template<class T> friend B; Is what has been used in the examples up until now a better syntax? I think so, because the template parameter specification is part of the type of what is being defined. However, allowing that requires a minor grammar change. Making template<class T> a type-specifier might simplify the grammar while achieving the desired effect. +------- END BOX 8 -------+ +------- BEGIN BOX 9 -------+ There is no way of declaring a specialization of a static member with out also defining it. For example: template<class T> class X { static T s; }; X<int> s; // definition, can't just declare One answer to this is to do nothing and hope there is little real need for a solution. Another answer is to introduce a separate keyword to indicate specialization; see Spicer 6.18 . +------- END BOX 9 -------+ 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); // call f<int>(int*) f(&b); // call f<char*>(char**) } Here f<int>(int*) has a static member s of type int and f<char*>(char**) has a static member s of type char*.