简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM