C++模板运算符重载具有不同类型的内容

C++ template operator overloading with different types

本文关键字:同类型 运算符 重载 C++      更新时间:2023-10-16

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

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

提前谢谢。

#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;
}

导致编译器输出:

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){

编辑:

下面的朋友方法为我完成了这项工作:

template<typename U, typename W>
friend PodObject<U> operator+= (PodObject<U> &lhs, PodObject<W> const &rhs) {
    lhs._value += rhs._value;
    return lhs;
} 
您需要

模板化operator +,因为您正在尝试添加不同的类型:

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

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