C++模板运算符重载具有不同类型的内容
C++ template operator overloading with different types
下面的示例定义了一个基本的 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;
}
您需要
模板化operator +
,因为您正在尝试添加不同的类型:
template <typename U>
PodObject<T> operator+= (PodObject<U> const &rhs){
this->_value = rhs._value;
return *this;
}
也就是说,整个代码看起来像一个反模式。您的"基本 podtype 的 OOP 版本"不是一个有意义的概念,也不是通常有用的概念。
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- JS相等运算符(如===)是否可以使用embind类型
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- 将所有模板类型传递给运算符,而不指定所有类型
- 标准库类型的赋值运算符的引用限定符
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- 如何确保接受的C++模板类型使运算符重载?
- C2678 二进制 '==':未找到采用 'Card' 类型左操作数的运算符(或者没有可接受的转换)
- 如何使用运算符在同一行中多次调用函数
- C2679 二进制"<<":未找到采用右操作数类型的运算符
- 使用类型id运算符的最佳替代方法
- 为什么 std::make_shared 无法编译带有已删除运算符 new 的类型?
- int* 和 int[] 类型对二进制运算符 + 的操作数无效
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 表达式必须具有类类型(运算符)
- 使用许多类型运算符过载时,模棱两可的超载
- 类型转换为类型&&运算符
- 返回类型 ?:运算符和 C++ Primer 中的措辞
- 返回类型与返回类型(运算符++)不相同,也不协变