C++模板运算符使用不同类型重载

Roy*_*Roy 2 c++ templates types overloading operator-keyword

下面的示例定义了一个基本的podtype容器类.然后使用此类创建一系列typedef,它们表示基本podtype的OOP版本.当我们开始将这些类型分配给彼此时,问题就产生了.

我尝试将运算符定义为使用lhs和rhs参数的友元方法,使用普通的PodObjects作为类型,但没有任何成功.有没有人可能经历过类似的事情或知道这个问题的其他解决方案.

提前致谢.

#include <stdint.h>

template <typename T>
class PodObject {
protected:
    T _value;

public:
    PodObject<T>(int rhs) {
        this->_value = static_cast<T>(rhs);
    }   

    PodObject<T> operator+= (PodObject<T> const &rhs){
        this->_value = rhs._value;
        return *this;
    }   
};  

typedef PodObject<int8_t> Int8;
typedef PodObject<int16_t> Int16;

int main() {
    Int16 a = 10; 
    Int8 b = 15; 

    a += b; // Source of problem
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果在编译器输出中:

example.cpp:26:11: error: no viable overloaded '+='
        a += b;
        ~ ^  ~
example.cpp:13:22: note: candidate function not viable: no known conversion from 'Int8' (aka 'PodObject<int8_t>') to 'const PodObject<short>'
      for 1st argument
        PodObject<T> operator+= (PodObject<T> const &rhs){
Run Code Online (Sandbox Code Playgroud)

编辑:

下面的朋友方法为我做的工作:

template<typename U, typename W>
friend PodObject<U> operator+= (PodObject<U> &lhs, PodObject<W> const &rhs) {
    lhs._value += rhs._value;
    return lhs;
} 
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 5

你需要一个模板,operator +因为你试图添加不同的类型:

template <typename U>
PodObject<T> operator+= (PodObject<U> const &rhs){
    this->_value = rhs._value;
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

也就是说,整个代码看起来像一个反模式.您的"基本podtype的OOP版本"不是一个有意义的,也不是一般有用的概念.