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 put 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 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, , therefore compiler wouldn't able instantiate template.

a common solution write template declaration in header file, implement class in implementation file (for example .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 keep 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 use foo int or float 

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


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -