0
4

1 回答 1

4

创建工厂:

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}
    {
    }
};
于 2018-10-12T14:44:46.930 回答