Julien Fouilhé
Julien Fouilhé

Reputation: 2658

How to specialize a class template member function?

I have a class template, which is, simplified, a little like that :

template<typename T>
class A
{
protected:
    T _data;
public:
    A* operator%(const A &a2) const
    {
        A * ptr;

        ptr = new A(this->_data % a2._data);
        return ptr;
    }
};

And another class which inherits from this class :

class B : public A<double>
{
    // ...
};

But when I do that, the compiler says :

 invalid operands of types ‘double’ and ‘const double’ to binary ‘operator%’

Then, I tried to specialize my operator% for double and float because % seems impossible for those types. I added the following code after class A declaration.

template<>
A* A<double>::operator%(const A &a2) const
{
    A * ptr;
    ptr = new A((uint32_t)this->_data % (uint32_t)a2._data);
    return ptr;
}

And I get this error, I don't actually understand why...

In function `A<double>::operator%(A const&) const':
./include/A.hpp:102: multiple definition of `A<float>::operator%(A const&) const'
src/Processor.o:./include/A.hpp:102: first defined here

Upvotes: 2

Views: 139

Answers (2)

Arne Mertz
Arne Mertz

Reputation: 24576

That is because unlike "real" templates, full function template specializations are like normal functions in terms of linking and ODR. And since you specialized it outside any class, it is not implicitly declared inline like a normal method defined inside a class definition.

Therefore you have either to declare the function inline, or only declare it in the header and define it in a source file like any normal function.

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258548

If you implemented the specialization, outside the class, it's no longer inline so it will be defined multiple times. Mark it inline:

template<>
inline A* A<double>::operator%(const A &a2) const
{
    A * ptr;
    ptr = new A(this->_data % a2._data);
    return ptr;
}

or move it inside the class definition.

Upvotes: 7

Related Questions