Lets say I have a class like so:
template< typename T, int nDimensions = 2 >
class Vec
{
private:
std::array< T, nDimensions > elements_;
}
Then I typedef out a few different types.
typedef Vec< int, 2 > Vec2i;
typedef Vec< int, 3 > Vec3i;
typedef Vec< float, 2 > Vec2f;
typedef Vec< float, 3 > Vec3f;
What would the constructor be if I wanted to convert from one type to another?
Vec2i something(10,20); //10,20
Vec2f somethingElse(something); //10.0f,20.0f
Same goes for different sizes:
Vec3f somethingmore(something); //10.0f,20.0f,0.0f
So far I have:
template<typename F>
Vec(const F& other)
{
for (int i = 0; i < nDimensions; i++)
{
this->elements_[i] = static_cast<F>(other[i]); //I know this is wrong.
}
}
I cant figure out a good way to get the base type of the other class to do the static casts on each element, nor a good way to get the others nDimension size so I can do proper bounds checking.
What would the constructor be if I wanted to convert from one type to another?
The most generic constructor would be:
template <typename T2, int nDimension2>
Vec(Vec<T2, nDimension2> const& copy) { ... }
That will need appropriate logic to make sure that you don't access memory using out of bounds indices.
A less generic constructor would be:
template <typename T2>
Vec(Vec<T2, nDimension> const& copy) { ... }
Here, you can use std::copy
to copy the elements.
template <typename T2>
Vec(Vec<T2, nDimension> const& copy) { std::copy(copy.elements_.begin(),
copy.elements_.ennd(),
this->elements_.begin()); }
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.