【发布时间】:2018-05-06 23:20:12
【问题描述】:
我正在尝试在工厂模式中创建一个递归函数,该函数通过可变数量的元素迭代 std::tuple。我已经像这样创建了我的 ConsoleShapeFactory:
template<size_t N, typename...Shapes>
class ConsoleShapeFactory : public ShapeFactory {
private:
//Functions for shape creation
void MakePoint(std::shared_ptr<CAD::Point>);
//Recursive Router for shapes
void MakeShapeRouter(std::tuple<Shapes...>&);
public:
//Create Object Function
std::tuple<Shapes...> CreateShapeTuple();
};
CreateShapeTuple 方法定义如下:
template<size_t N, typename...Shapes>
std::tuple<Shapes...> ConsoleShapeFactory<N, Shapes...>::CreateShapeTuple() {
//Define return tuple and get size
std::tuple<Shapes...> returnTuple;
MakeShapeRouter(returnTuple);
return returnTuple;
}
而递归的 MakeShapeRouter 函数看起来像这样(这不起作用):
template<size_t N, typename...Shapes>
void ConsoleShapeFactory<N, Shapes...>::MakeShapeRouter(std::tuple<Shapes...>& tupShapes) {
MakePoint(std::tuple::get<N-1>(tupShapes));
ConsoleShapeFactory<N-1, Shapes...>::MakeShapeRouter(tupShapes); //This doesn't work
}
我在基本情况下的尝试如下所示:
template<size_t N, typename...Shapes>
void ConsoleShapeFactory<1, Shapes...>::MakeShapeRouter(std::tuple<Shapes...>& tupShapes) {
MakePoint(std::tuple::get<0>(tupShapes));
}
我不确定如何设置我的 MakeShapeRouter 函数,以便可以递归调用它并以基本情况退出。我正在尝试做的事情是否可能?
*编辑
如果有帮助,我想在我的 main 方法中调用该函数:
int main()
{
auto factory = ConsoleShapeFactory<2, std::shared_ptr<CAD::Point>, std::shared_ptr<CAD::Point>>();
std::tuple<std::shared_ptr<CAD::Point>, std::shared_ptr<CAD::Point>> shapeTuple = factory.CreateShapeTuple();
return 0;
}
*编辑 2
MakePoint 实现:
template<typename...Shapes>
void ConsoleShapeFactory<Shapes...>::MakePoint(std::shared_ptr<CAD::Point>& sp_point) {
double x, y;
x = 3;
y = 4;
sp_point = std::make_shared<CAD::Point>(x,y);
};
【问题讨论】:
标签: c++ recursion variadic-templates