Templates and LNK2005

In a header file, I have a template with some inline methods:

template <class BASE>
class ServiceTmpl : public BASE
{
virtual string const& name() const { return name_; }
...
};

Another file has an abstract base:

class IInstrumentFactory
{
virtual void variousMethods() = 0;
};

Then I have two classes:

class NullInstrumentFactory : public ServiceTmpl<IInstrumentFactory>;

class G3InstrumentFactory : public ServiceTmpl<IInstrumentFactory>;

Now I'm getting LNK2005 errors, because apparently ServiceTmpl<IInstrumentFactory> is being instantiated twice. How can I avoid this problem



Answer this question

Templates and LNK2005

  • Il-Sung Lee - MSFT

    You shouldn't get linker errors there. Can you copy/paste the exact error messages please

    tyronen wrote:

    In a header file, I have a template with some inline methods:

    template <class BASE>
    class ServiceTmpl : public BASE
    {
    virtual string const& name() const { return name_; }
    ...
    };

    Another file has an abstract base:

    class IInstrumentFactory
    {
    virtual void variousMethods() = 0;
    };

    Then I have two classes:

    class NullInstrumentFactory : public ServiceTmpl<IInstrumentFactory>;

    class G3InstrumentFactory : public ServiceTmpl<IInstrumentFactory>;

    Now I'm getting LNK2005 errors, because apparently ServiceTmpl<IInstrumentFactory> is being instantiated twice. How can I avoid this problem



  • David Reeves

    The template will only be instantiated once within the translation unit. You probably instantiated non-inline member functions (virtual function definitions are automatically instantiated, when any ctor is instantiated)

    You get two definitions of the member functions which violates the One Definition Rule. However, you can make these functions inline (either implicit by providing the implementation in the class body or with the inline keyword)

    As always small compilable repros and exact error messages are quite helpful ;-)

    -hg


  • Templates and LNK2005