c++ - 如何专门化类模板成员函数?

标签 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;
    }
};

还有一个继承自此类的类:

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

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

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

然后,我尝试将我的 operator% 专门化为 doublefloat,因为 % 对于这些类型来说似乎是不可能的。我在 class 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;
}

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

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

最佳答案

如果您在类外实现了特化,它就不再是内联的,所以它会被定义多次。将其标记为内联:

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

或将其移动到类定义中。

关于c++ - 如何专门化类模板成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14872582/

相关文章:

c++ - 堆栈 View - 解释

android - delphi XE7 firemonkey android共享对象/库动态加载-模板

css - 缩放页面 (ctr+ ctr-),折叠模板

C++ - 在单元测试中创建 spy

c++ - 成员函数的 std::forward 和 ref 限定符

c++ - 使用 enable_if 的模板特化

c++ - 复制/分配 STL 模板,std::less 和 std:greater

c++ - 在 SDL2 中加载同一图像的多个纹理

C++ 最终类和切片习惯用法

c++ - vs2005和vs2010模板函数的优先级不同