Why can templates only be implemented in the header file?

来源:互联网 发布:validate.js 示例 编辑:程序博客网 时间:2024/06/05 02:21

Quote from The C++ standard library: a tutorial and handbook:

The only portable way of using templates at the moment is to implement them in header files by using inline functions.

Why is this?


Because when instantiating a template, the compiler creates a new class with the given template argument. For example:

template<typename T>struct Foo{    T bar;    void doSomething(T param) {/* do stuff using T */}};// somewhere in a .cppFoo<int> f; 

When reading this line, the compiler will create a new class (let's call it FooInt), which is equivalent to the following:

struct FooInt{    int bar;    void doSomething(int param) {/* do stuff using int */}}

Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.

A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.

// Foo.htemplate <typename T>struct Foo{    void doSomething(T param);};#include "Foo.tpp"// Foo.tpptemplate <typename T>void Foo<T>::doSomething(T param){    //implementation}


This way, implementation is still separated from declaration, but is accessible to the compiler.

Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:

// Foo.h// no implementationtemplate <typename T> struct Foo { ... };//----------------------------------------    // Foo.cpp// implementation of Foo's methods// explicit instantiationstemplate class Foo<int>;template class Foo<float>;// You will only be able to use Foo with int or float


If my explanation isn't clear enough, you can have a look at the C++ FaqLite on this subject.


0 0
原创粉丝点击