C ++模板运算符使用不同类型重载 [英] C++ template operator overloading with different types

查看:195
本文介绍了C ++模板运算符使用不同类型重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的示例定义了一个基本的podtype容器类。使用这个类,然后创建一系列typedef,它们表示基本podtype的OOP版本。

The example below defines a basic podtype container class. Using this class a series of typedefs are then created which represent an OOP version of the basic podtype. The problem originates when we start assigning those types to one another.

我试图将操作符定义为friend方法,使用lhs和rhs参数,使用plain PodObjects作为类型,但没有任何成功。是否有任何人可能遇到过这种问题的模拟或知道其他解决方案。

I tried to define the operator as friend method with lhs and rhs arguments using plain PodObjects as type but without any succes. Is there anyone who might have experienced something simular or knows an other solution for this problem.

提前感谢。

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






编辑:


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

The friend method below does the job for me:

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


推荐答案

c $ c> operator + ,因为您尝试添加不同类型:

You need a templated operator + because you are trying to add different types:

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

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

That said, the whole code looks like an anti-pattern. Your "OOP version of the basic podtype" is not a meaningful, nor generally useful, concept.

这篇关于C ++模板运算符使用不同类型重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆