U
U.Mutlu
This is about a template linking problem:
Below we have a struct TS1, a template class TC1 and a non-template class TC2.
TC2::f() calls TC1<TS1>::f(), it compiles, but linker brings error.
I don't understand why, normally it should work I think.
Why must one place template code in header file?
What's the reason the following doesn't link?
I would like to hide the iplementation by doing it in the cpp file.
Is there a workaround to get this compiled+linked?
//-------- inc.hpp -------------
struct TS1
{
};
struct TS2
{
};
template<typename T = TS1> class TC1
{
public:
TC1();
void f();
};
extern TC1<> gC1;
class TC2
{
public:
TC2();
void f();
};
//-------- file1.cpp -----------
#include "inc.hpp"
template<typename T> TC1<T>::TC1()
{
}
template<typename T> void TC1<T>::f()
{
}
TC1<> gC1;
int main(int argc, char* argv[])
{
TC2 C2;
C2.f();
return 0;
}
//-------- file2.cpp -----------
#include "inc.hpp"
TC2::TC2()
{
}
void TC2::f()
{
gC1.f();
}
## Build g++: g++ file1.cpp file2.cpp
## Build MSC++: cl file1.cpp file2.cpp
Below we have a struct TS1, a template class TC1 and a non-template class TC2.
TC2::f() calls TC1<TS1>::f(), it compiles, but linker brings error.
I don't understand why, normally it should work I think.
Why must one place template code in header file?
What's the reason the following doesn't link?
I would like to hide the iplementation by doing it in the cpp file.
Is there a workaround to get this compiled+linked?
//-------- inc.hpp -------------
struct TS1
{
};
struct TS2
{
};
template<typename T = TS1> class TC1
{
public:
TC1();
void f();
};
extern TC1<> gC1;
class TC2
{
public:
TC2();
void f();
};
//-------- file1.cpp -----------
#include "inc.hpp"
template<typename T> TC1<T>::TC1()
{
}
template<typename T> void TC1<T>::f()
{
}
TC1<> gC1;
int main(int argc, char* argv[])
{
TC2 C2;
C2.f();
return 0;
}
//-------- file2.cpp -----------
#include "inc.hpp"
TC2::TC2()
{
}
void TC2::f()
{
gC1.f();
}
## Build g++: g++ file1.cpp file2.cpp
## Build MSC++: cl file1.cpp file2.cpp