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. Help?
Provide an additional constructor that's taking another template parameter 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
.
Note that this has nothing to do with your original vector being const
. Instead, you're trying to construct a value of type Vector2<int>
with a value of another type Value2<double>
. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.