C ++ templates: are header files still broken?

It used to be that in order to use the template class in C ++, implementations should be in the header file or # included in the header file below.

I have not used C ++ templates for several years; I just started using them and noticed that this behavior seems to persist. Is this still true? Or are the compilers smart enough to implement the implementation separately from the interface?

+3
source share
5 answers

Technically they don't need in the header file.

- (, sake char wchar_t). . , , .

// X.h
template<typename T>
class X
{
     // DECLARATION ONLY OF STUFF
     public:
       X(T const& t);
     private:
       T m_t;
};

// X.cpp
#include "X.h"

// DEFINTION OF STUFF
template<typename T>
X<T>::X(T const& t)
    :m_t(t)
{}

// INSTANCIATE The versions you want.
template class X<char>;
template class X<wchar_t>;


// Main.cpp
#include "X.h"

int main()
{
    X<chat>    x1('a');
    X<wchar_t> x2(L'A');
    // X<int>     x3(5);   // Uncomment for a linker failure.
}

, X.cpp( ), X <int> X <float> .. abovr .

, . X, ( , ). , X, .

+3

, export. , , , : .

++ 0x , , ( ). , , , extern.

+2

( export), , -, ++ ( ++ FAQ Lite).

, , "", .

+2

EDG, Comeau, .

, .

, "" . , , ... , , , , .

" ", Sutters blog, pdf ( google ), , , :)

(, .hpp .ipp), , .

foo.hpp

#ifndef MY_TEMPLATES_HPP
#define MY_TEMPLATES_HPP

template< class T >
void foo(T & t);

#include "foo.ipp"
#endif

foo.ipp

#ifdef MY_TEMPLATES_IPP
  nonsense here, that will generate compiler error
#else
#define MY_TEMPLATES_IPP

template< class T >
void foo(T & t) {
   ... // long function
}

#endif

, , .

+1

GCC goes through a lengthy collection phase unless you explicitly create an instance of all the templates. VC ++ seems to do the trick, but I prefer to avoid this step anyway, and in cases where I know how to use the template, which is usually used for applications and not for libraries, I put the template definitions in a separate file . It also makes the code more readable, making declarations less cluttered with implementation details.

0
source

Source: https://habr.com/ru/post/1718809/


All Articles