模板;点<2,双>;点<3,双> [英] template; Point<2, double>; Point<3, double>
问题描述
我想创建自己的 Point 结构,它仅用于学习 C++.
我有以下代码:
I want to create my own Point struct it is only for purposes of learning C++.
I have the following code:
template <int dims, typename T>
struct Point {
T X[dims];
Point(){}
Point( T X0, T X1 ) {
X[0] = X0;
X[1] = X1;
}
Point( T X0, T X1, T X2 ) {
X[0] = X0;
X[1] = X1;
X[2] = X2;
}
Point<dims, int> toint() {
//how to distinguish between 2D and 3D ???
Point<dims, int> ret = Point<dims, int>( (int)X[0], (int)X[1]);
return ret;
}
std::string str(){
//how to distinguish between 2D and 3D ???
std::stringstream s;
s << "{ X0: " << X[0] << " | X1: " << X[1] << " }";
return s.str();
}
};
int main(void) {
Point<2, double> p2d = Point<2, double>( 12.3, 45.6 );
Point<3, double> p3d = Point<3, double>( 12.3, 45.6, 78.9 );
Point<2, int> p2i = p2d.toint(); //OK
Point<3, int> p3i = p3d.toint(); //m???
std::cout << p2d.str() << std::endl; //OK
std::cout << p3d.str() << std::endl; //m???
std::cout << p2i.str() << std::endl; //m???
std::cout << p3i.str() << std::endl; //m???
char c; std::cin >> c;
return 0;
}
当然到目前为止输出不是我想要的.我的问题是:如何在Point的成员函数中处理Point的维度(2D或3D)?
of couse until now the output is not what I want. my questions is: how to take care of the dimensions of the Point (2D or 3D) in member functions of the Point?
非常感谢
糟糕
推荐答案
你的维度在编译时是固定的,通过模板argumnt dims
,所以你可以迭代它们:
Your dimensions are fixed at compile time, by the template arguemnt dims
, so you can iterate over them:
std::string str(){
//how to distinguish between 2D and 3D ???
std::stringstream s;
s << "{ ";
std::copy( X, X+dims, std::ostream_iterator<T>( s, "|") );
s << " }";
return s.str();
}
此外,您可以根据 dims
提供构造函数:
Also, you can provide a constructor in terms of the dims
:
Point( const T (&c) [dims] ){
std::copy( c, c+dims, X );
}
这允许像 double[] d={1,2,3}; 这样的代码.Point<3,double>p(d);
,它把关于参数数量的决定放在别处.
This allows for code like double[] d={1,2,3}; Point<3,double> p(d);
, which puts the decision on the number of arguments elsewhere.
对于cast-to-point-of-ints"构造函数,您只需使用 Point
作为参数:
For the 'cast-to-point-of-ints' constructor you just can use Point
as the argument:
Point<dims,int> toint() const {
Point<dims,int> result;
std::copy( X, X+dims, result.X );
return result;
}
这篇关于模板;点<2,双>;点<3,双>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!