[英]C++ template operator overloading with different types
下面的示例定義一個基本的podtype容器類。 然后使用此類創建一系列typedef,這些typedef表示基本podtype的OOP版本。 當我們開始將這些類型彼此分配時,就會出現問題。
我試圖將操作員定義為帶有lhs和rhs參數的朋友方法,並使用普通PodObjects作為類型,但是沒有任何成功。 是否有人可能經歷過類似的事情或知道此問題的其他解決方案。
提前致謝。
#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版本”不是有意義的概念,也不是普遍有用的概念。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.