[英]C++ typecast overloading
Supposed I have a class like this: 假设我有一个这样的课:
template<class T>
class Vector2 {
public:
Vector2(const T a, const T b) : x(a), x(b) {}
T x;
T y;
}
I want to be able to do something like this: 我希望能够做这样的事情:
const Vector2<double> d(31.4, 48.2); // note the const!!!
Vector2<int> i = static_cast<Vector2<int>>(d);
// i.x == 31
// i.y == 48
I have tried overloading a generic operator but it seems to break when trying to convert from a const value. 我曾尝试重载通用运算符,但在尝试从const值转换时似乎会中断。 Help? 救命?
Provide an additional constructor that's taking another template parameter U
: 提供另一个采用另一个模板参数U
构造函数:
template<class T>
class Vector2 {
public:
template <class U>
Vector2(const Vector2<U> & other) : x(other.x), y(other.y){}
// other code ommited
};
After all, you're trying to use Vector2<T>::Vector2(const Vector2<U> &)
, where U = double
and T = int
. 毕竟,您尝试使用Vector2<T>::Vector2(const Vector2<U> &)
,其中U = double
和T = int
。
Note that this has nothing to do with your original vector being const
. 请注意,这与原始向量const
。 Instead, you're trying to construct a value of type Vector2<int>
with a value of another type Value2<double>
. 相反,您尝试使用另一个类型Value2<double>
的值构造Vector2<int>
类型的值。 Those are distinct types, and therefore you need to provide a constructor. 这些是不同的类型,因此您需要提供一个构造函数。
A possibility would be to write a cast operator which does what you want: 一种可能是编写执行所需操作的强制转换运算符:
template<class T>
class Vector2 {
public:
Vector2(const T a, const T b) : x(a), y(b) {}
T x;
T y;
template<typename U>
operator Vector2<U>() const { return Vector2<U>( (U)x, (U)y ); }
// ^^^^^^^^ cast operator
};
int main()
{
const Vector2<double> d(31.4, 48.2); // note the const!!!
Vector2<int> i = static_cast<Vector2<int>>(d);
return 0;
}
An additional constructor as shown in the answer of Zeta is the much more elegant solution. Zeta答案中显示的另一个构造函数是更优雅的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.