[英]Conversion between 2 template types
我有一个类的代码(这是一个片段):
template<typename T>
class Pos2 {
public:
T x, y;
Pos2() : x(0), y(0) {};
Pos2(T xy) : x(xy), y(xy) {};
Pos2(T x, T y) : x(x), y(y) {};
};
现在,我还有2个typedef:
typedef Pos2<pos_scalar> Pos;
typedef Pos2<size_scalar> Size;
一切都按预期工作,但当我这样做时:
Pos p(5.5, 6.5);
Size s(3, 8);
p = s;
我收到此错误:
error: conversion from ‘Size {aka Pos2<short int>}’ to non-scalar type ‘Pos’ requested
这很有道理,但我想知道如何修复它= P.
添加构造函数
template <typename Type2> Pos2(const Pos2<Type2> &other)
{ x = other.x; y = other.y; }
您需要定义一个赋值运算符,用于从类型Size
到类型Pos
赋值,因为它们不是同一类型,因此两者之间没有默认赋值运算符。
我想你想在这里使用一个模板,所以Pos2
任何实例化都可以用来分配给另一个实例。 例如:
template<typename T>
class Pos2 {
public:
T x, y;
Pos2() : x(0), y(0) {};
Pos2(T xy) : x(xy), y(xy) {};
Pos2(T x, T y) : x(x), y(y) {};
template<typename FromT>
Pos2<T>& operator=(const Pos2<FromT>& from) {
x = from.x;
y = from.y;
return *this;
}
};
您应该对复制构造函数(此处未显示)执行相同的操作,因为您可能希望在某个时刻在同一方案中复制构造。
这仅适用于类型T
和FromT
之间的赋值,即pos_scalar
和size_scalar
。 如果不是,请尝试为赋值运算符添加正确的显式转换和/或模板特化。
此外,如果Pos2
任何成员是私人/受保护的,您将需要与分配操作员交friend
或提供足够的getter。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.