【问题标题】:C++ template operator overloading with different types不同类型的 C++ 模板运算符重载
【发布时间】:2012-04-26 13:30:03
【问题描述】:

下面的示例定义了一个基本的 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;
} 

【问题讨论】:

    标签: c++ templates types overloading operator-keyword


    【解决方案1】:

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

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

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

    【讨论】:

    • 这更像是一个实验,而不是理智的东西,是的,我会为此而去程序员地狱:)。但是感谢您的回答,但是成员变量需要公开才能使其正常工作。
    • 成员变量不需要是public,如果你让PodObjects 成为彼此的朋友:template&lt;class T&gt; friend PodObject&lt;T&gt;; P.S.如果你真的交付了这段代码,你只会去程序员的地狱。
    猜你喜欢
    • 2021-09-15
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    相关资源
    最近更新 更多