[英]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.