没有公共构造函数作为另一个类模板成员的类模板

class template without public constructor as member of another class template

本文关键字:成员 另一个 构造函数      更新时间:2023-10-16

我有一个类模板Shape,其中包含有关某些形状(可以是三维或二维(的信息。我只希望有几个预定义的形状(立方体、球体和正方形(可用。所有这些预定义的形状都具有相同的属性(因此立方体始终具有相同的体积,我只需要记住一个立方体的属性(。为了禁止某人创建其他Shape,我使构造函数private

// Flag for the possible shapes
enum class Tag
{
SPHERE,
CUBE,
SQUARE
};
template<std::size_t N>
class Shape
{
public:
// Predefined shapes.
static const Shape<3> SPHERE;
static const Shape<3> CUBE;
static const Shape<2> SQUARE;
// Information stored about the given shapes
const Tag tag; // tag specifying the shape
const double v; // Shape volume/area
const std::array<double, 2*N> surrounding_box; // Storing intervals for a surrounding box
//... Some other information that depends on template parameter N
private:
// Private constructor. This prevents other, unintended shapes from being created
Shape(Tag tag, double v, const std::array<double, 2*N> surrounding_box):
tag{tag}, v {v}, surrounding_box {surrounding_box} {};
};
// Initialization of predefined shape: SPHERE
template<std::size_t N>
const Shape<3> Shape<N>::SPHERE(Tag::SPHERE, 3.0,{{0.0,2.7,0.0,2.7,0.0,2.7}});
// Initialization of predefined shape: CUBE
template<std::size_t N>
const Shape<3> Shape<N>::CUBE(Tag::CUBE, 1.0,{{0.0,1.0,0.0,1.0,0.0,1.0}});
// Initialization of predefined shape: SQUARE
template<std::size_t N>
const Shape<2> Shape<N>::SQUARE(Tag::SQUARE, 1.0,{{0.0,1.0,0.0,1.0}});

现在我可以得到一个立方体,作为:

Shape<3> cube = Shape<3>::CUBE;

这似乎工作正常。

当我想将Shape实例作为另一个类模板的成员时出现问题Object.具体来说,我无法为我的Object类模板编写正常工作的构造函数:

template <std::size_t N>
class Object
{
public:
Object(Tag shape_tag, double weight, double elevation):
weight {weight}, elevation {elevation}
{
switch(shape_tag)
{
case Tag::CUBE:
{
shape = Shape<3>::CUBE;
break;
}
case Tag::SPHERE:
{
shape = Shape<3>::SPHERE;
break;
}
case Tag::SQUARE:
{
shape = Shape<2>::SQUARE;
break;
}
}
}
private:
Shape<N> shape;
double weight;
double elevation;
};

创建Object

Object<3> object(Tag::CUBE, 1.0,1.0);

失败,编译器错误error: no matching function for call to ‘Shape<3ul>::Shape()’。 我认为,因为我不使用初始值设定项列表来shapeObject的构造函数尝试调用默认构造函数Shape(),这是不可用的。 我还尝试将构造的Shape部分移动到单独的初始化函数,然后我可以在初始值设定项列表中调用该函数。但是,在这种情况下,模板部分不断生成不同的问题(因为我需要能够同时初始化Shape<2>Shape<3>对象(。

我该如何解决这个问题?或者是否有更好的方法来确保只有一些预定义的Shape可用,而不使其构造函数私有?

附言。这里介绍的形状和对象的问题只是一个MWE。

创建工厂:

template <std::size_t N> Shape<N> MakeShape(Tag shape_tag);
template <>
Shape<3> MakeShape(Tag shape_tag)
{
switch(shape_tag)
{
case Tag::CUBE: return Shape<3>::CUBE;
case Tag::SPHERE: return Shape<3>::SPHERE;
}
throw std::runtime_error("Invalid tag");
}
template <>
Shape<2> MakeShape(Tag shape_tag)
{
switch(shape_tag)
{
case Tag::SQUARE: return Shape<3>::SQUARE;
}
throw std::runtime_error("Invalid tag");
}

然后

template <std::size_t N>
class Object
{
public:
Object(Tag shape_tag, double weight, double elevation):
shape{MakeShape<N>(shape_tag)}, weight {weight}, elevation {elevation}
{
}
};
相关文章: