假设我有这样一个类:
template< typename T, int nDimensions = 2 >
class Vec
{
private:
std::array< T, nDimensions > elements_;
}
然后我输入了几个不同的类型。
typedef Vec< int, 2 > Vec2i;
typedef Vec< int, 3 > Vec3i;
typedef Vec< float, 2 > Vec2f;
typedef Vec< float, 3 > Vec3f;
如果我想从一种类型转换为另一种类型,构造函数应该是什么?
Vec2i something(10,20); //10,20
Vec2f somethingElse(something); //10.0f,20.0f
同样适用于不同的尺寸:
Vec3f somethingmore(something); //10.0f,20.0f,0.0f
到目前为止我有:
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.
}
}
我想不出一个让其他类的基类型对每个元素进行静态转换的好方法,也想不出一个好方法来获取其他 nDimension 大小以便我可以进行适当的边界检查。
最佳答案
What would the constructor be if I wanted to convert from one type to another?
最通用的构造函数是:
template <typename T2, int nDimension2>
Vec(Vec<T2, nDimension2> const& copy) { ... }
这将需要适当的逻辑来确保您不会使用越界索引访问内存。
一个不太通用的构造函数是:
template <typename T2>
Vec(Vec<T2, nDimension> const& copy) { ... }
在这里,您可以使用std::copy
来复制元素。
template <typename T2>
Vec(Vec<T2, nDimension> const& copy) { std::copy(copy.elements_.begin(),
copy.elements_.ennd(),
this->elements_.begin()); }
关于c++ - 构造函数中的模板类转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50120704/