为模板中的元组创建递归函数



我正在尝试在工厂模式中创建一个递归函数,该函数遍历具有可变数量元素的 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);
};

你的方法不是static的,所以你需要一个实例来调用它们。

ConsoleShapeFactory<N-1, Shapes...>::MakeShapeRouter(tupShapes); //This doesn't work

应该是

ConsoleShapeFactory<N-1, Shapes...>{}.MakeShapeRouter(tupShapes);

但是由于std::index_sequence,事情可以在没有递归的情况下完成,例如:

template<typename... Shapes>
class ConsoleShapeFactory : public ShapeFactory {
private:
//Functions for shape creation
void MakePoint(std::shared_ptr<CAD::Point>);
template <std::size_t ... Is>
std::tuple<Shapes...> CreateShapeTuple(std::index_sequence<Is...>)
{
std::tuple<Shapes...> res;
(MakePoint(std::get<Is>(res)), ...); // C++17
/* or C++11
const int dummy[] = {0, (MakePoint(std::get<Is>(res)), 0)...};
static_cast<void>(dummy); // Avoid warning for unused variable.
*/
return res;
}
public:
//Create Object Function
std::tuple<Shapes...> CreateShapeTuple() {
return CreateShapeTuple(std::index_sequence_for<Shapes...>());
}
};

最新更新