简体   繁体   中英

C++ template operator overloading with different types

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.

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.

Thanks in advance.

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

Results in a compiler output:

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

EDIT:

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM