定義多維的點模板類,任意資料型別

wkdlilin發表於2018-08-10
#include <iostream>
#include <assert.h>
using namespace std;
template <class type, int dim>
class Point{
public:
Point();
Point(type coords[dim]){
     for(int idx = 0; idx < dim; idx ++){
      _coords[idx] = coords[idx];
    }
}
type &operator [] (int idx){
    assert ( idx < dim && idx >= 0);
    return _coords[idx];
}
type operator [] (int idx) const{
        assert ( idx < dim && idx >= 0);
        return _coords[idx];
}
private:
type _coords[dim];
};
template <class type, int dim>
inline
ostream & operator << (ostream & os,  const Point<type, dim> &pt){
os << "(";
for (int idx = 0; idx < dim -1; idx ++)
    os << pt[idx] << " , ";
os << pt[dim -1];
os << ")";
}
//example
int main() {
    cout  << "test\n";
    float t_f[3] = {0.0f, 0.1f,0.2f};
    Point<float, 3> t_pt(t_f);
    cout << t_pt; 
    return 0;
}

//result
簡單測試執行結果展示

相關文章