如何使用给定数量的变量创建一个类?

时间:2017-11-26 05:12:31

标签: c++ templates

我想使用模板类并根据给定的int数。应该选择上课。

代码:

template<3>
    class  Point
    {
    private:
        double x;
        double y;
        double z;
    };
template<2>
    class  Point
    {
    private:
        double x;
        double y;
    };

怎么做?

2 个答案:

答案 0 :(得分:0)

你可能想要template specialization。见这个例子:

// Add a template and make it empty
template <size_t N>
class Point {};

// Specialize it!
template <>
class Point<3>
{
    private:
    double x;
    double y;
    double z;
};
template <>
class Point<2>
{
    private:
    double x;
    double y;
};

您甚至可以使用推导使Point<3>Point<2>兼容!

template <>
class Point<3> : public Point<2>
{
    private:
    // No need to add x and y as they're inherited
    double z;
};

答案 1 :(得分:-1)

您可以将模板参数声明为int:

#include <iostream>
#include <array>

template<int N>
class Point {
public:
  std::array<double,N> _coordinates;
  void Print();
};

template<int N>
void Point<N>::Print()
{
  for (int i=0; i<N; ++i)
    std::cout << _coordinates[i] << "  ";
  std::cout << "\n";
}


int main()
{
  Point<4> A;
  A._coordinates[0] = 1;
  A._coordinates[1] = 8;
  A._coordinates[2] = -101;
  A._coordinates[3] = 999;
  A.Print();
  return 0;
}