我想使用模板类并根据给定的int数。应该选择上课。
代码:
template<3>
class Point
{
private:
double x;
double y;
double z;
};
template<2>
class Point
{
private:
double x;
double y;
};
怎么做?
答案 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;
}