如何从新运算符+(Template类)返回具有转换类型的对象
How can I return an object with converted type from a new operator+ (Template class)
我为球体编写了一个模板类。它保存了它们的中心点和半径。现在,我正在尝试编写一个operator+
,它为中心点的每个值添加一个值。我的主函数调用如下:
Sphere<int, double> s1(1,1,1,2.5); // (x,y,z,radius)
auto s2 = s1 + 1.5;
而我的operator+
看起来是这样的:
template <typename T, typename S> class Sphere {
...
template <typename U>
friend Sphere operator+(const Sphere<T, S> s, U add){ // Sphere<int, double>
decltype(s.m_x + add) x,y,z;
x = s.m_x + add;
y = s.m_y + add;
z = s.m_z + add;
Sphere<decltype(x), S> n(x,y,z,s.rad); // now Sphere<double, double>
return n; //error occurs here
}
};
我得到的错误消息是:
could not convert 'n' from 'Sphere<double, double>' to 'Sphere<int, double>'
我必须改变什么才能奏效?为什么我的方法错了?
friend
函数的返回类型中的Sphere
指的是封闭类的类型,因此它是Sphere<int, double>
。使用尾部返回类型指定正确的类型
template <typename U>
friend auto operator+(Sphere<T, S> const& s, U add)
-> Sphere<decltype(s.m_x + add), S>
{ ... }
或者,如果您有一个支持函数推导返回类型的C++14编译器,那么只需删除尾部返回类型即可。
template <typename U>
friend auto operator+(Sphere<T, S> const& s, U add)
{ ... }
因此,在您的示例中,您有return n
,n由Sphere<int, double>
和Sphere<double, double>
组成。它会给您错误,因为您的值类型为int
,而double
是编译器在其他Sphere
函数中期望的类型。
示例:
int number;
double(number);
或
static_cast<double>(number);
相关文章:
- 返回时不允许隐式转换
- 基于返回类型的转换和过载扣除
- 将传入的网络"char*"数据转换为"uint8_t"并返回的安全方法是什么?
- 将内存分配返回值强制转换为 TYPE 数组
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 用户定义的转换无法指定返回类型
- 使用 jni 将返回带有模板的对象的 Java 代码转换为 c++
- 如何为具有常量类型的函数正确转换来自 DLsym 的返回值?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 类型转换问题:返回为整数而不是浮点/类型
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 如何定义依赖于参数包转换的函数的返回类型
- 将unique_ptr转换为void*并返回,我需要释放吗
- 函数返回动态强制转换的指针,返回指针,就好像它根本没有被转换一样
- 从类型bankAccount的返回值到函数返回类型int没有可行的转换
- 为什么在std::for_each()返回时调用转换运算符
- 隐式转换函数的返回对象时是否会影响性能?
- 类型映射资源并将列表转换为矢量(并返回)
- 将 MPFR 数字转换为字符串并返回
- 如何将C++引用和指针返回转换为 C++/CLR