The following code (this is a simplified version of what I need) does not link
In *.h file:
class InterfaceFunctionField2 {
public:
template<class outputType> outputType to() { return outputType(); }
};
In *.cpp file
template<> double InterfaceFunctionField2::to<double>()
{ return 3.; }
This class sits in a static library.
I am getting "error LNK2005: "public: double __thiscall InterfaceFunctionField2::to(void)const " (??$to@N@InterfaceFunctionField2@@QBENXZ) already defined in ..." and a "second definition ignored" warning LNK4006
I define InterfaceFunctionField2::to() specialization only once and I do not #include *.cpp files....
I have looked up on internet (e.g. here) and this type of code seems to be ok but the linker disagrees. Could you help? Thanks.
You need to also declare the specialization in the header.
//header.h
class InterfaceFunctionField2 {
public:
template<class outputType> outputType to() { return outputType(); }
};
template<> double InterfaceFunctionField2::to<double>();
//implementation.cc
template<> double InterfaceFunctionField2::to<double>()
{ return 3.; }
The code in your link works because the specialization is visible to that translation unit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With