[英]C++ typecast overloading
假设我有一个这样的课:
template<class T>
class Vector2 {
public:
Vector2(const T a, const T b) : x(a), x(b) {}
T x;
T y;
}
我希望能够做这样的事情:
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
我曾尝试重载通用运算符,但在尝试从const值转换时似乎会中断。 救命?
提供另一个采用另一个模板参数U
构造函数:
template<class T>
class Vector2 {
public:
template <class U>
Vector2(const Vector2<U> & other) : x(other.x), y(other.y){}
// other code ommited
};
毕竟,您尝试使用Vector2<T>::Vector2(const Vector2<U> &)
,其中U = double
和T = int
。
请注意,这与原始向量const
。 相反,您尝试使用另一个类型Value2<double>
的值构造Vector2<int>
类型的值。 这些是不同的类型,因此您需要提供一个构造函数。
一种可能是编写执行所需操作的强制转换运算符:
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;
}
Zeta答案中显示的另一个构造函数是更优雅的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.