Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specialize a class template member function?

Tags:

c++

templates

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
like image 474
Julien Fouilhé Avatar asked May 28 '26 00:05

Julien Fouilhé


1 Answers

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.

like image 187
Luchian Grigore Avatar answered May 30 '26 15:05

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!