C++ Specializing single member function

Viewed 89

Problems with class template member specialization.

I have a simple class and I want specialize a single member function. I'm doing like this:

template <class T>
class Object
{
public:
    Object() {}

    void print() const
    {
        std::cout << "It's the template" << std::endl;
    }
    // ...
};

template<>
void Object<int>::print() const
{
    std::cout << "It's an int" << std::endl;
}

which ends up in a compile error for multiple definition of the member function.

If just one source file includes the header everything is fine.

If two files include the header I get the following error:

/home/marc/QtProjects/QtAsp-Service/build-aspservice-Desktop_Qt_5_15_0_GCC_64bit-Debug/../src/Asp/aspobject.h:34: Fehler: multiple definition of `Asp2::print()'; main.o:/home/marc/QtProjects/QtAsp-Service/build-aspservice-Desktop_Qt_5_15_0_GCC_64bit-Debug/../src/Asp/aspobject.h:34: first defined here

This this possible in general? If yes, what is wrong.

2 Answers

Your way is correct, but fully specialized member is no longer template, so no longer implicitly inline.

You have to add inline if you keep definition in header, or split declaration (in header) and definition (in cpp).

template<>
inline void Object<int>::print()
{
    std::cout << "It's an int" << std::endl;
}

The problem was that the template class is defined in a seperate header file. If only one source file includes the header it works. If two or more source files include the header GCC throws a multiple definition error. Is there a other way of doing it?

Related