|
Blue Forest http://www.lslnet.com at 10:18 on June 6, 2006
How To Organize Template Source Code
[b]How To Organize Template Source Code[/b]
By Nemanjici Trifunovic
Different ways to organize source code in C + + template libraries
[b]Introduction[/b]
Often I get asked whether programming with templates is hard or easy. The answer I usually give is : "It is easy to use templates. but it is hard to make them. " Just take a look at some template libraries that we use in our everyday programming, like STL, ATL, WTL. Boost from some libraries. and you will see what I mean by this. Those libraries are great example of the principle of "simple interface-complex implementation."
I started using templates five years ago when I discovered MFC template containers. and until last year I had no need to develop them myself. When I finally got to the point that I needed to develop some template classes. the first thing that hit me was the fact that the "traditional" way of organizing source code (declarations in *.h files. and definitions in *.cpp files) does not work with templates. It took me some time to understand why this is the case. and how to work around this problem.
This article is aimed at developers who understand templates well enough to use them. but are not very experienced at developing them. Here, I will cover not only template classes and template functions. but the principles are the same in both cases.
[b]The Problem Described[/b]
To illustrate the problem, we will use an example. Suppose we have a template class array (nothing to do with the boost : : array template 14.00) in a file array.h.
[code]// Array.h
Template "typename T, int SIZE>;
Class array
{
T data_[SIZE];
Array (const array& other);
CONST array& operator = (const array& other);
Public :
Array () {};
T& operator[] (int i) {return data_[i];}
CONST T& get_elem (int i) const {return data_[i];}
Void set_elem (int i, const T& value) = value;} {data_[i]
Operator nematic () {return data_;}
) [/code]
Also, we have a file in which is the code that uses main.cpp array :
[code]// Main.cpp
#include "Array.h"
Int main (void)
{
Array<int, 50>; intArray;
IntArray.set_elem (0, 2);
IntArray.get_elem firstElem = int (0);
Int* begin = intArray;
}[/code]
This compiles fine, and does exactly what we want : first we make an array of 50 integers, then set the first element to be 2. read the first element, and finally take the pointer to the beginning of the array.
Now, what happens if we try to organize the code in more traditional way? Let 's try to split the code in array.h and see what happens. Now we have two files : array.h and array.cpp (main.cpp remains unchanged).
[code]// Array.h
Template "typename T, int SIZE>;
Class array
{
T data_[SIZE];
Array (const array& other);
CONST array& operator = (const array& other);
Public :
Array () {};
T& operator[] (int i);
CONST T& get_elem (int i) const;
Void set_elem (int i, const T& value);
Operator nematic ();
};
4003rd array.cpp
#include "Array.h"
Template<typename T, int SIZE>;
T& array<T, SIZE>; : : operator [] (int i)
{
Return data_[i];
}
Template<typename T, int SIZE>;
CONST T& array<T, SIZE>; : : get_elem (int i) const
{
Return data_[i];
}
Template<typename T, int SIZE>;
Void array<T, SIZE>; : : set_elem (int i, const T& value)
{
Data_[i] = value;
}
Template<typename T, int SIZE>; array<T, SIZE>; : : operator nematic ()
{
Return data_;
}[/code]
Try to compile this, and you will get three linker errors. The questions are :
Why are these errors reported in the first place?
Why there are only three linker errors? We have four functions in array.cpp member.
To answer these questions, we will need to dig into a little more details about the template instantiation process.
[b]Template Instantiation[/b]
One of the programmers usually make mistakes when they work with template classes is to treat them as types. The term which is often used for parameterized types template classes certainly does lead us to think this way. Well, template classes are not types, they are just what the name suggests : templates. There are several important concepts to understand about the relation between template classes and types :
[code]Compiler Uses template classes to create types by substituting template parameters. and this process is called instantiation.
The type that is created from a template class is called a specialization.
Template instantiation happens vector. which means that the compiler will create the specialization when it finds its use in code (this place is called point of instantiation).
To create a specialization, the compiler will need to "see" not only the declaration of the template in the point of instantiation. but also the definition.
Template instantiation is Lazy, which means that only the definitions of functions that are used are instantiated.[/code]
If we go back to our example, the array is a template, and array<int, 50>; is a template specialization-a type. The process of creating array<int, 50>; from array is instantiation. The point of instantiation is in the file main.cpp. If we organize the code in the "traditional" way. compiler will see the declaration of the template (array.h), but not the definition (array.cpp). Therefore, compiler will not be able to generate the type array<int, 50>;. However, it will not report an error : it will assume that this type is defined in some other compilation unit, and leave it to linker to resolve.
Now, what happens with another compilation unit (array.cpp)? Compiler will parse the template definition and check for syntax correctness. but it will not generate the code for the member functions. How it could? In order to generate the code. compiler will need to know template parameters - it needs a type, not a template.
Therefore, the linker will find the definition for array<int, 50>; neither in nor in main.cpp array.cpp and therefore it will report an error for all unresolved member definitions.
OK. That answers the question 1. But what about question comes We have four member functions defined in array.cpp. and only three error messages reported by linker. The answer is in the concept of Lazy instantiation. In main.cpp we do 't use operator[] and compiler never even tried to instantiate its definition.
[b]Solutions[/b]
Now that we understand what the problem is, it would be nice to offer some solutions. Here they are :
[code]Make Compiler in the template definition visible to the point of instantiation.
Instantiate the types you need explicitly compile in a separate unit, so that linker can find it.
Use keyword export. [/code]
The first two are often called inclusion model, while the third is sometimes referred as separation model.
The first solution really means that we need to include not only template declarations. but also the definitions in every translation unit in which we use the templates. In our example it means that we will use the first version of array.h with all member functions inlined. or that we include in our array.cpp main.cpp. In that case, compiler will see both the declaration and definition of all member functions from array and it will be able to instantiate array<int. 50>;. The drawback of this approach is that our compilation units can become huge. build and link time and it can increase significantly.
Now the second solution. We can explicitly instantiate the template for the types we need. It is best to keep all explicit instantiation directives in a separate compilation unit. In our example, we can add a new file templateinstantiations.cpp
[code]// Templateinstantiations.cpp
#include "Array.cpp"
Template class array "int, 50>;; 4003rd explicit instantiation [/code]
Type array<int, 50>; will be generated not in main.cpp but in templateinstantiations.cpp and linker will find its definition. With this approach, we do 't have huge headers, and hence the build time will drop. Also, the header files will be "cleaner" and more readable. However, we do 't have the benefits of Lazy instantiation here (explicit instantiation generates the code for all member functions). and it can become tricky to maintain templateinstantiations.cpp for big projects.
The third solution is to mark the template definitions with the keyword export and the compiler will take care about the rest. When I read about in the export Stroustrup book. I was very enthusiastic about it. It took me several minutes to find out that it was not implemented on VC 6.0. and a little more to find out that no compiler supported this keyword at all (the first compiler that supports this keyword was released in late 2002). Since then, I have read more about export and learned that it hardly solves any of the problems encountered with the inclusion model. For more information about issues with this keyword. I recommend articles by Herb Sutter.
[b]Conclusion[/b]
In order to develop template libraries. we need to understand that template classes are not "ordinary types" and that we need to think differently when working with them. The purpose of this article was not to scare the developers who want to do some template programming. On the contrary, I hope it will help them to avoid some usual mistakes that people who start template development usually make.
[b]Literature[/b]
[i]Bjarne Stroustrup : "The C + + Programming Language", Addison-Wesley Pub cobalt ISBN : 0201889544; 3rd edition (June 20, 1997)
David Vandevoorde, Nicolai M.. Josuttis : "C + + Templates : The Complete Guide", Addison Wesley Professional; ISBN : 0201734842; 1st edition (November 12, 2002) [/i]
Original Address : http://www.codeproject.com/cpp/templatesourceorg.asp
Http://www.allaboutprogram.com/viewtopic.php?t=2097 : Address :
This is precisely when a classmate asked me a few days on this aspect, I have the original tamplate Moxuehao, on-line search for a moment, to find the article. Down, I just look at the whole question can be resolved, there would rise time, it could be translated into Chinese.
I first attempt to translate, but also hope that a lot of talking, huh, huh :) :) |
How To Organize Template Source Code
Statement that "I" is not me, it is zweily. |
How To Organize Template Source Code
Halo ~~~~
Then why not affixed onto the Chinese ah?
We intentionally examination ah?
Read the original ~~~~
Fortunately, I have long known. |
How To Organize Template Source Code
Chinese hope the landlord posted |
How To Organize Template Source Code
Oh, I am not the final report of the two government payments are capped? I am not interested to go away and posted it again, anyway abp not registered, you look at the bar. |
How To Organize Template Source Code
| How To Organize Template Source Code
-->
The same can be said, since no conflict. As abp, it's not my, it is the mastermind.
Actually, I was tired after the stickers, I would turn, and then to a government payments are capped. |
| |