lundi 25 avril 2016

Why templates are not redefined why all is written in the header file?

If I will write something like this:

// A.h
#ifndef A_h
#define A_h
class A
{
public:
void f();
};

void A::f()
{
}
#endif //A_h


// B.cpp
#include "A.h"

void foo()
{
    A a;
    a.f();
}


// C.cpp
#include "A.h"

void bar()
{
    A b;
    b.f();
}

// main.cpp
#include "B.cpp"
#include "C.cpp"
using namespace std;


int main()
{
    foo();
    bar();
    return 0;
}

I get such a linker error:

error LNK2005: "public: void __thiscall A::f(void)" (?f@A@@QAEXXZ) already defined in B.obj

But why the same problem does not happen when A class is a template class. Eventually it is becoming a plain class (a non-template one) during compilation, right? For this reason, I expect the same behavior as a non-template class works, i.e. a linker error.

Aucun commentaire:

Enregistrer un commentaire