1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
8 |
|
1 2 |
|
[Originally written sometime in December, 2006. Fixed a couple markup errors, changed some wording, and added a little bit 12/23/2007. I still don't quite consider it complete; I haven't explained all the rules yet. I have a ranty version of what I want to add here; start reading where it says "[RESUMING]" if you read this document first.]
The purpose of this document is to describe the reasoning behind the inclusion of the typename keyword in standard C++, and explain where, when, and how it can and can't be used.
There is a use of typename that is entirely distinct from the main focus of this discussion. I will present it first because it is easy. It seems to me that someone said "hey, since we're adding typename anyway, why not make it do this" and people said "that's a good idea."
Most older C++ books, when discussing templates, use the following type of example:
template <class T> ...
I know when I was starting to learn templates, at first I was a little thrown by the fact that T was prefaced by class, and yet it was possible to instantiate that template with primitive types such as int. The confusion was very short-lived, but the use of class in that context never seemed to fit entirely right. Fortunately for my sensibilities, it is also possible to use typename:
template <typename T> ...
This means exactly the same thing as the previous instance. The typename and class keywords can be used interchangeably to state that a template parameter is a type variable (as opposed to a non-type template parameter).
I personally like to use typename in this context because I think it's ever so slightly clearer. And maybe not so much "clearer" as just conceptually nicer. (I think that good names for things are very important.) Some C++ programmers share my view, and use typename for templates. (However, later we will see how it's possible that this decision can hurt readibility.) Some programmers make a distinction between templates that are fully generic (such as the STL containers) and more special purpose ones that can only take certain classes, and use typename for the former category and class for the latter. Others use class exclusively. This is just a style choice.
However, while I use typename in real code, I will stick to class in this document to reduce confusion with the other use of typename.
This discussion I think follows fairly closely appendix B from the book C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond by David Abrahams and Aleksey Gurtovoy, though I don't have it in front of me now. If there are any deficiencies in my discussion of the issues, that book contains the clearest description of them that I've seen.
There are two key concepts needed to understand the description of typename, and they are qualified and dependent names.
A qualified name is one that specifies a scope. For instance, in the following C++ program, the references to cout and endl are qualified names:
#include <iostream>
int main() {
std::cout %lt;%lt; "Hello world!" %lt;%lt; std:: endl;
}
In both cases, the use of cout and endl began with std::.
Had I decided to bring cout and endl into scope with a using declaration or directive*, they would have been unqualified names, because they would lack the std::.
(* Remember, a using declaration is like using std::cout;, and actually introduces the name cout into the scope that the using appears in. A using directive is of the form using namespace std; and makes names visible but doesn't introduce anything. [12/23/07 -- I'm not sure this is true. Just a warning.])
Note, however, that if I had brought them into scope with using but still used std::cout, it remains a qualified name. The qualified-ness of a name has nothing to do with what scope it's used in, what names are visible at that point of the program etc.; it is solely a statement about the name that was used to reference the entity in question. (Also note that there's nothing special about std, or indeed about namespaces at all. vector<int>::iterator is a nested name as well.)
A dependent name is a name that depends on a template parameter. Suppose we have the following declaration (not legal C++):
template <class T>
class MyClass {
int i;
vector<int> vi;
vector<int>::iterator vitr;
T t;
vector<T> vt;
vector<T>::iterator viter;
};
The types of the first three declarations are known at the time of the template declaration. However, the types of the second set of three declarations are not known until the point of instantiation, because they depend on the template parameter T.
The names T, vector<T>, and vector<T>::iterator are called dependent names, and the types they name are dependent types. The names used in the first three declarations are called non-dependent names, at the types are non-dependent types.
The final complication in what's considered dependent is that typedefs transfer the quality of being dependent. For instance:
typedef T another_name_for_T;
another_name_for_T is still considered a dependent name despite the type variable T from the template declaration not appearing.
Note: I am not very familiar with the notion of dependent types in the type theory sense, but they are not quite the same thing in any case. My impression is that you could probably argue a C++ template itself is a dependent type in the type-theoretical sense, but the C++ notion of a dependent type is more like the argument to a dependent type in the type-theoretical sense.
Note that while there is a notion of a dependent type, there is not a notion of a qualified type. A type can be unqualified in one instance, and qualified the next; the qualification is a property of a particular naming of a type, not of the type itself. (Indeed, when a type is first defined, it is always unqualified.)
However, it will be useful to refer to a qualified type; what I mean by this is a qualified name that refers to a type. I will switch back to the more precise wording when I talk about the rules of typename.
So now we can consider the following example:
template <class T>
void foo() {
T::iterator * iter;
...
}
What did the programmer intend this bit of code to do? Probably, what the programmer intended was for there to be a class that defined a nested type called iterator:
class ContainsAType {
class iterator { ... }:
...
};
and for foo to be called with an instantiation of T being that type:
foo<ContainsAType>();
In that case, then line 3 would be a declaration of a variable called iter that would be a pointer to an object of type T::iterator (in the case of ContainsAType, int*, making iter a double-indirection pointer to an int). So far so good.
However, what the programmer didn't expect is for someone else to come up and declare the following class:
class ContainsAValue {
static int iterator;
};
and call foo instantiated with it:
foo<ContainsAValue>();
In this case, line 3 becomes a statement that evaluates an expression which is the product of two things: a variable called iter (which may be undeclared or may be a name of a global) and the static variable T::iterator.
Uh oh! The same series of tokens can be parsed in two entirely different ways, and there's no way to disambiguate them until instantiation. C++ frowns on this situation. Rather than delaying interpretation of the tokens until instantiation, they change the languge:
Before a qualified dependent type, you need typename
To be legal, assuming the programmer intended line 3 as a declaration, they would have to write
template <class T>
void foo() {
typename T::iterator * iter;
...
}
Without typename, there is a C++ parsing rule that says that qualified dependent names should be parsed as non-types even if it leads to a syntax error. Thus if there was a variable called iter in scope, the example would be legal; it would just be interpreted as multiplication. Then when the programmer instantiated foo with ContainsAType, there would be an error because you can't multiply something by a type.
typename states that the name that follows should be treated as a type. Otherwise, names are interpreted to refer to non-types.
This rule even holds if it doesn't make sense even if it doesn't make sense to refer to a non-type. For instance, suppose we were to do something more typical and declare an iterator instead of a pointer to an iterator:
template <class T>
void foo() {
typename T::iterator iter;
...
}
Even in this case, typename is required, and omitting it will cause compile error. As another example, typedefs also require use:
template <class T>
void foo() {
typedef typename T::iterator iterator_type;
...
}
from:
http://pages.cs.wisc.edu/~driscoll/typename.html
A template is a way to specify generic code, with a placeholder for the type. Note that the type is the only "parameter" of a template, but a very powerful one, since anything from a function to a class (or a routine) can be specified in "general" terms without concerning yourself about the specific type. Yet. These details are postponed until you start to use the template. You can consider templates to be compile-time polymorphic, yet typesafe (in contrast to C MACROs).
Function vs. Class
When talking about C++ templates, one should realize that there are, in
fact, two kinds of templates: function templates and class templates.
The former are quite easy to implement, because they usually only
contain the template(s) in their definition. As an example of a function
template, here is a function that produces the minimum of two
arguments, without specifying the actual type of the arguments:
template <typename T>
T max(const T &X, const T &Y)
{
if (X > Y)
return X;
else
return Y;
}
T is the usual template character that is used to specify the typename,
which鈥攁t the time of definition鈥攊s unknown, and will be determined when
you actually use the template in your source code. Here is an example:
int x = max(6, 42); // compiler determines T = int
float y = max(3.1415927, 2.20371); // compiler determines T = float
Or explicitly, as follows:
int x = max<int> (6, 42); // explicit template syntax
The C++ compiler will be able to determine鈥攁t compile time鈥攚here the
calls to this function template are made, which argument types are used,
and hence which "expansions" of this function template have to be
generated (like a MACRO expansion) and then compiled and linked into an
executable. All this is happening behind the scenes, of course, although
template expansion can take a lot of compiler and linker resource (as
you may find out when you start to use them more often).
Class templates are similar to function templates in that the compiler will determine at compile-time which expansions (or instantions) of the class template are needed. The fact that they are classes and not merely functions, makes the syntax a bit more difficult, however.
Pop Quiz
Even if you're an experienced C++ class template user, could you tell me
from the top of your head what the syntax would be of the
implementation skeleton for the copy constructor of a template class
TDerived, which is derived from a template class TBase? You have 10
seconds ...
It turns out to be as follows:
template <class T> TDerived<T>::TDerived(const TDerived<T>& copy): TBase<T>(copy)
But I don't blame you if you couldn't come up with that right away. If
you did know the answer, then you probably don't need to read the
remainder of this article, unless you're also interested in a
template-based template header/source generator. That's what I made for
myself, to help me remember.
Canonical Class
But before I want to continue with class templates, let's first talk
about a minimum useful class, sometimes also called a canonical class.
By this I mean a class definition which is minimal (only a few key
methods), but still complete and useful. This means that the class
should at least contain the default constructor (without an argument),
the destructor, a copy constructor, the assignment operator, the compare
operator and last鈥攐ptionally鈥攖he stream operator (always useful when
debugging). When a class contains at least these methods, we can call it
a canonical class.
Since I'm planning to produce a template header and source generator, it's important to realise what I should generate and what not. Making sure that I produce a canonical class鈥攅specially when it comes to templates, can make the difference between a nice but useless or an actual useful tool. As an example, here is the canonical class definition (header file) of a class TBase:
class TBase
{
public:
// Constructors & Destructors
TBase(void);
TBase(const TBase& copy);
virtual ~TBase(void);
// Operator overloading
TBase& operator = (const TBase& other);
int operator == (const TBase& other) const;
// Output
friend ostream& operator << (ostream& os, const TBase& other);
};
template <class T> class TBase
Just to let you know what the implementation looks like (the empty
{
public:
// Constructors & Destructors
TBase(void);
TBase(const TBase<T>& copy);
virtual ~TBase(void);
// Operator overloading
TBase<T>& operator = (const TBase<T>& other);
int operator == (const TBase<T>& other) const;
// Output
friend ostream& operator << (ostream& os, const TBase<T>& other);
};
skeletons, that is), take a look at the following listing:// Constructors & Destructors
template <class T> TBase<T>::TBase(void) {}
template <class T> TBase<T>::TBase(const TBase<T>& copy) {}
template <class T> TBase<T>::~TBase(void) {}
// Operator overloading
template <class T> TBase<T>& TBase<T>::operator = (const TBase<T>& other) {}
template <class T> int TBase<T>::operator == (const TBase<T>& other) const {}
// Output
template <class T> ostream& operator << (ostream& os, const TBase<T>& other) {}
This is usually the place where I could do with a little help or support
to get the class template syntax right.
Derived Templates
If you've been able to keep up with me so far, then let's get to the
final round: templates derived from other templates. Sometimes you just
have to derive your own custom class template TDerived from a base
template class TBase (sound familiar?).
And just for your amusement (and mine), I've included the header listing
for the derived canonical class template definition below:
template <class T> class TDerived: public TBase<T>
{
public:
// Constructors & Destructors
TDerived(void);
TDerived(const TDerived<T>& copy);
virtual ~TDerived(void);
// Operator overloading
TDerived<T>& operator = (const TDerived<T>& other);
int operator == (const TDerived<T>& other) const;
// Output
friend ostream& operator << (ostream& os, const TDerived<T>& other);
};
Certainly this TDerived class template definition needs a list of empty
implementation skeletons, which are defined as follows (empty because
they're skeletons, but they still need to be implemented by the
programmer, of course).
// Constructors & Destructors
template <class T> TDerived<T>::TDerived(void): TBase<T>() {}
template <class T> TDerived<T>::TDerived(const TDerived<T>& copy): TBase<T>(copy) {}
template <class T> TDerived<T>::~TDerived(void) {}
// Operator overloading
template <class T> TDerived<T>& TDerived<T>::operator = (const TDerived<T>& other) {}
template <class T> int TDerived<T>::operator == (const TDerived<T>& other) const {}
// Output
template <class T> ostream& operator << (ostream& os, const TDerived<T>& other) {}
OK, who could already produce the above listing without a second
thought? If you could, then you probably didn't need to read this
article, because the fun stuff is over. What remains is the description
of a little tool that I made for myself to actually produce and generate
the output listings that we've seen so far.
// File: <#class>.hpp
Note the special #-tags. WebBroker developers may recognize these as
// Author: drs. Robert E. Swart>
// Date: <#date>
// Time: <#time>
// Version: 0.01
// Generated by: HeadGen (c) 1995-2001 by Bob Swart
(aka Dr.Bob - www.drbob42.com)
// Changes:
//
#ifndef <#class>_hpp
#define <#class>_hpp
#include <iostream.h>
<#includebase>
template <class <#templatechar>> class <#class> <#publicbase>
{
public:
// Constructors & Destructors
<#class>(void);
<#class>(const <#class><#template>& copy);
virtual ~<#class>(void);>
// Accessing functions
// Modifier functions
// Operator overloading
<#class><#template>& operator = (const <#class><#template>& other);
int operator == (const <#class><#template>& other) const;
// Streaming output
friend ostream& operator << (ostream& os, const <#class><#template>& other);
protected:
private:
};
#endif
tags used in the PageProducer components. That's actually the case,
since I'm using a TPageProducer component (from the Internet tab) to
expand the above template into a true class template definition
header鈥攚ith or without a template base class.
The same technique can be applied to the following template listing,
that can be used to produce the empty template skeleton implementations:// File: <#class>.cpp
// Author: drs. Robert E. Swart
// Date: <#date>
// Time: <#time>
// Version: 0.01
// Generated by: HeadGen (c) 1995-2001 by Bob Swart
(aka Dr.Bob - www.drbob42.com)
// Changes:
//
#include "<#include>.hpp"
// Constructors & Destructors
template <class <#templatechar>> <#class><#template>::<#class>(void) <#base>
<#body>
template <class <#templatechar>> <#class><#template>::<#class>(const
<#class><#template>& copy) <#basecopy>
<#body>
template <class <#templatechar>> <#class><#template>::~<#class>(void)
<#body>
// Operator overloading
template <class <#templatechar>> <#class><#template>& <#class><#template>::operator = (const <
#class><#template>& other)
<#body>
template <class <#templatechar>> int <#class><#template>::operator == (const
<#class><#template>& other) const
<#body>
// Streaming output
template <class <#templatechar>> ostream& operator << (ostream&
os, const <#class><#template>& other)
<#body>
Again, the above listing can be used to produce a stand-alone class
template as well as a derived class template. We only need to specify
three options: the class name, the (optional) base class name, and the
template character.
HeadGen
For the base class, specify Base in the Class Name box leave the Ancestor type box empty, and click on Generate. For the derived class, specify Derived in the Class Name box, Base in the Ancestor Type box and then click on Generate again. In both cases, the T will be added as prefix automatically (files Base.hpp and Base.cpp will contain the definition for TBase).
A very simple Borland C++Builder example program (to test the syntax of the generated files) can be seen below:
//---------------------------------------------------------
#pragma hdrstop
#include "Base.cpp" // TBase
#include "Derived.cpp"; // TDerived
//--------------------------------------------------------
typedef TDerived<int> TintClass;
#pragma argsused
int main(int argc, char* argv[])
{
TintClass* Bob = new TintClass();
TintClass Swart = TintClass(*Bob);
if (*Bob == Swart) { *Bob = Swart; }
return 0;
}
//--------------------------------------------------------
Note that I needed to include the .cpp files of the templates, and not
only (or just) the .hpp files. That's because the .cpp files are
"expanded" (like MACROs) to the compiler, which must find them in order
to be able to use them.
External Templates
from:
http://www.devx.com/cplus/Article/20689/0/page/1
// template_friend1.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
template <class T> class Array {
T* array;
int size;
public:
Array(int sz): size(sz) {
array = new T[size];
memset(array, 0, size * sizeof(T));
}
Array(const Array& a) {
size = a.size;
array = new T[size];
memcpy_s(array, a.array, sizeof(T));
}
T& operator[](int i) {
return *(array + i);
}
int Length() { return size; }
void print() {
for (int i = 0; i < size; i++)
cout << *(array + i) << " ";
cout << endl;
}
template<class T>
friend Array<T>* combine(Array<T>& a1, Array<T>& a2);
};
template<class T>
Array<T>* combine(Array<T>& a1, Array<T>& a2) {
Array<T>* a = new Array<T>(a1.size + a2.size);
for (int i = 0; i < a1.size; i++)
(*a)[i] = *(a1.array + i);
for (int i = 0; i < a2.size; i++)
(*a)[i + a1.size] = *(a2.array + i);
return a;
}
int main() {
Array<char> alpha1(26);
for (int i = 0 ; i < alpha1.Length() ; i++)
alpha1[i] = 'A' + i;
alpha1.print();
Array<char> alpha2(26);
for (int i = 0 ; i < alpha2.Length() ; i++)
alpha2[i] = 'a' + i;
alpha2.print();
Array<char>*alpha3 = combine(alpha1, alpha2);
alpha3->print();
delete alpha3;
}
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z
The next example involves a friend that has a template specialization. A function template specialization is automatically a friend if the original function template is a friend.
It is also possible to declare only the specialized version of the template as the friend, as the comment before the friend declaration in the following code indicates. If you do this, you must put the definition of the friend template specialization outside of the template class.
// template_friend2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
template <class T>
class Array;
template <class T>
void f(Array<T>& a);
template <class T> class Array
{
T* array;
int size;
public:
Array(int sz): size(sz)
{
array = new T[size];
memset(array, 0, size * sizeof(T));
}
Array(const Array& a)
{
size = a.size;
array = new T[size];
memcpy_s(array, a.array, sizeof(T));
}
T& operator[](int i)
{
return *(array + i);
}
int Length()
{
return size;
}
void print()
{
for (int i = 0; i < size; i++)
{
cout << *(array + i) << " ";
}
cout << endl;
}
// If you replace the friend declaration with the int-specific
// version, only the int specialization will be a friend.
// The code in the generic f will fail
// with C2248: 'Array<T>::size' :
// cannot access private member declared in class 'Array<T>'.
//friend void f<int>(Array<int>& a);
friend void f<>(Array<T>& a);
};
// f function template, friend of Array<T>
template <class T>
void f(Array<T>& a)
{
cout << a.size << " generic" << endl;
}
// Specialization of f for int arrays
// will be a friend because the template f is a friend.
template<> void f(Array<int>& a)
{
cout << a.size << " int" << endl;
}
int main()
{
Array<char> ac(10);
f(ac);
Array<int> a(10);
f(a);
}
10 genericThe next example shows a friend class template declared within a class template. The class template is then used as the template argument for the friend class. Friend class templates must be defined outside of the class template in which they are declared. Any specializations or partial specializations of the friend template are also friends of the original class template.
10 int
// template_friend3.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
template <class T>
class X
{
private:
T* data;
void InitData(int seed) { data = new T(seed); }
public:
void print() { cout << *data << endl; }
template <class U> friend class Factory;
};
template <class U>
class Factory
{
public:
U* GetNewObject(int seed)
{
U* pu = new U;
pu->InitData(seed);
return pu;
}
};
int main()
{
Factory< X<int> > XintFactory;
X<int>* x1 = XintFactory.GetNewObject(65);
X<int>* x2 = XintFactory.GetNewObject(97);
Factory< X<char> > XcharFactory;
X<char>* x3 = XcharFactory.GetNewObject(65);
X<char>* x4 = XcharFactory.GetNewObject(97);
x1->print();
x2->print();
x3->print();
x4->print();
}
65from錛?br>http://msdn.microsoft.com/en-us/library/f1b2td24.aspx
97
A
a