我想创建自己的Point结构,它只是为了学习C++.
我有以下代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,输出不是我想要的.我的问题是:如何在Point的成员函数中处理Point(2D或3D)的尺寸?
非常感谢
Oops
您的维度在编译时由模板arguemnt修复dims,因此您可以迭代它们:
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();
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以提供以下方面的构造函数dims:
Point( const T (&c) [dims] ){
std::copy( c, c+dims, X );
}
Run Code Online (Sandbox Code Playgroud)
这允许像这样的代码double[] d={1,2,3}; Point<3,double> p(d);,它决定其他地方的参数数量.
对于'cast-to-point-of-ints'构造函数,您可以使用它Point作为参数:
Point<dims,int> toint() const {
Point<dims,int> result;
std::copy( X, X+dims, result.X );
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2216 次 |
| 最近记录: |