Monday 15 March 2010

c++ - Why can templates only be implemented in the header file? -



c++ - Why can templates only be implemented in the header file? -

quote the c++ standard library: tutorial , handbook:

the portable way of using templates @ moment implement them in header files using inline functions.

why this?

(clarification: header files not only portable solution. convenient portable solution.)

it not necessary set implementation in header file, see alternative solution @ end of answer.

anyway, reason code failing that, when instantiating template, compiler creates new class given template argument. example:

template<typename t> struct foo { t bar; void dosomething(t param) {/* stuff using t */} }; // somewhere in .cpp foo<int> f;

when reading line, compiler create new class (let's phone call fooint), equivalent following:

struct fooint { int bar; void dosomething(int param) {/* stuff using int */} }

consequently, compiler needs have access implementation of methods, instantiate them template argument (in case int). if these implementations not in header, wouldn't accessible, , hence compiler wouldn't able instantiate template.

a mutual solution write template declaration in header file, implement class in implementation file (for illustration .tpp), , include implementation file @ end of header.

// foo.h template <typename t> struct foo { void dosomething(t param); }; #include "foo.tpp" // foo.tpp template <typename t> void foo<t>::dosomething(t param) { //implementation }

this way, implementation still separated declaration, accessible compiler.

another solution maintain implementation separated, , explicitly instantiate template instances you'll need:

// foo.h // no implementation template <typename t> struct foo { ... }; //---------------------------------------- // foo.cpp // implementation of foo's methods // explicit instantiations template class foo<int>; template class foo<float>; // able utilize foo int or float

if explanation isn't clear enough, can have @ c++ super-faq on subject.

c++ templates c++-faq

No comments:

Post a Comment