Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trivial specialization of a method does not work (c++)

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.

like image 841
Yulia V Avatar asked Dec 19 '25 05:12

Yulia V


1 Answers

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.

like image 155
Luchian Grigore Avatar answered Dec 21 '25 18:12

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!