如何专门化一个类模板成员函数?

Jul*_*lhé 2 c++ templates

我有一个类模板,简化,有点像:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

另一个继承自这个类的类:

class B : public A<double>
{
    // ...
};
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,编译器说:

 invalid operands of types ‘double’ and ‘const double’ to binary ‘operator%’
Run Code Online (Sandbox Code Playgroud)

然后,我试图将我operator%的专用于doublefloat,因为%似乎不可能用于那些类型.我在A类声明后添加了以下代码.

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

我得到这个错误,我实际上不明白为什么......

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
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 7

如果您在类之外实现了特化,则它不再是内联的,因此将多次定义.将其标记为内联:

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

或者在类定义中移动它.