我想实现一个简单的多维点类与模板(学习)。我需要两个专业Point2D和Point3D - 这是我迄今为止允许构造函数直接初始化Point Point(像点1,2)一样。虽然这段代码编译并正常工作,但我不喜欢的是专业化中的代码重复部分 - 我一定在做错事。C++模板 - 简单点类
我是新来的C + + /模板 - 任何帮助表示赞赏。
#ifndef POINT_H_
#define POINT_H_
template< typename T, int Dimensions = 2 >
class Point
{
public:
typedef typename T value_type;
Point() { std::fill(elements_, elements_+Dimensions, 0); }
Point(const Point<T, Dimensions>& rhs) : elements_(rhs.elements_) {}
~Point() {}
Point & operator=(const Point<T, Dimensions>& rhs) { return *this; }
const Point operator+(const Point<T, Dimensions>& p)
{
Point<T, Dimensions> ret;
for(int i = 0; i < Dimensions; i++)
{
ret[i] += elements_[i] + p[i];
}
return ret;
}
Point & operator+=(const Point<T, Dimensions>& p)
{
for(int i = 0; i < Dimensions; i++)
{
elements_[i] += p[i];
}
return *this;
}
Point & operator-=(const Point<T, Dimensions> & p)
{
for(int i = 0; i < Dimensions; i++)
{
elements_[i] -= p[i];
}
return *this;
}
T & operator[](const size_t index)
{
return elements_[index];
}
private:
T elements_[Dimensions];
};
template<typename T>
class Point< T, 2 >
{
public:
Point(const T x, const T y)
{
elements_[0] = x;
elements_[1] = y;
}
typedef typename T value_type;
Point() { std::fill(elements_, elements_+Dimensions, 0); }
Point(const Point<T, 2>& rhs) : elements_(rhs.elements_) {}
~Point() {}
Point & operator=(const Point<T, 2>& rhs) { return *this; }
const Point operator+(const Point<T, 2>& p)
{
Point<T, 2> ret;
for(int i = 0; i < 2; i++)
{
ret[i] += elements_[i] + p[i];
}
return ret;
}
Point & operator+=(const Point<T, 2>& p)
{
for(int i = 0; i < 2; i++)
{
elements_[i] += p[i];
}
return *this;
}
Point & operator-=(const Point<T, 2> & p)
{
for(int i = 0; i < 2; i++)
{
elements_[i] -= p[i];
}
return *this;
}
T & operator[](const size_t index)
{
return elements_[index];
}
private:
T elements_[2];
};
template< typename T>
class Point< T, 3 >
{
public:
Point(const T x, const T y, const T z)
{
elements_[0] = x;
elements_[1] = y;
elements_[2] = z;
}
typedef typename T value_type;
Point() { std::fill(elements_, elements_+3, 0); }
Point(const Point<T, 3>& rhs) : elements_(rhs.elements_) {}
~Point() {}
Point & operator=(const Point<T, 3>& rhs) { return *this; }
const Point operator+(const Point<T, 3>& p)
{
Point<T, 3> ret;
for(int i = 0; i < 3; i++)
{
ret[i] += elements_[i] + p[i];
}
return ret;
}
Point & operator+=(const Point<T, 3>& p)
{
for(int i = 0; i < 3; i++)
{
elements_[i] += p[i];
}
return *this;
}
Point & operator-=(const Point<T, 3> & p)
{
for(int i = 0; i < 3; i++)
{
elements_[i] -= p[i];
}
return *this;
}
T & operator[](const size_t index)
{
return elements_[index];
}
private:
T elements_[3];
};
typedef Point< int, 2 > Point2Di;
typedef Point< int, 3 > Point3Di;
#endif //POINT_H_
我不明白,你需要在所有专注这个类的任何原因。它应该都没有专业化(除了可能的一些小调整)。 – Chad 2012-08-09 20:34:19
在我看来,您可以将大量重复代码放入您的主类和它的专业化派生自的通用基类中。 – jahhaj 2012-08-09 20:36:49
@Chad,我想要专注于此的唯一原因是为了方便添加构造函数Point(T x,T y)。 –
user1588625
2012-08-09 20:42:59