以下の例では、基本的なポッドタイプコンテナクラスを定義しています。次に、このクラスを使用して、基本的なポッドタイプのOOPバージョンを表す一連のtypedefが作成されます。問題は、これらのタイプを相互に割り当て始めたときに発生します。
プレーンな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){
編集:
以下のfriendメソッドは私のために仕事をします:
template<typename U, typename W>
friend PodObject<U> operator+= (PodObject<U> &lhs, PodObject<W> const &rhs) {
lhs._value += rhs._value;
return lhs;
}