gpt4 book ai didi

c++ - 避免在模板参数中积累迭代器类型

转载 作者:搜寻专家 更新时间:2023-10-31 01:27:23 26 4
gpt4 key购买 nike

遵循以下原则:当我想从函数返回一个集合时,我将传递一个输出迭代器并让调用者决定输出的位置。

考虑具有 n 方法的类,每个方法都返回一些集合。这意味着我需要使用 n 模板参数(输出迭代器)构造类。模板参数的数量将开始增长,我不知道如何处理这个问题。

具体例子:

template<class TNode, class TEdge> class AGraph;
template<class TNode, class TEdge, class OutputOfFunc1, class OutputOfFunc2>
class APathCalculation
{
using TGraph = AGraph<TNode, TEdge>;
public:
virtual void ReturnShortestPath(size_t source, size_t dest, TGraph& graph, OutputOfFunc1 outPath) = 0;//func1
virtual void ReturnAllShortestDistances(size_t source, TGraph& graph, OutputOfFunc2 outDistances) = 0;//func2
};

并且,我将从 APathCalculation 派生不同的类(例如 Dijkstra、Bellman-Ford)。但问题是我引入了模板参数

...class OutputOfFunc1, class OutputOfFunc2>

我认为它们不应该出现在类定义中,因为它们特定于特定功能。

目前我是这样声明类的

// Example of declaration
APathCalculation<
int, // type of node
double, // type of edge
back_insert_iterator<list<size_t>>, // return type of shortest path between two nodes
back_insert_iterator<vector<double>> // return type of shortest distances from source node
> &pathCalculator;

最佳答案

"Consider the class which has n methods and each one returns some collection. This mean that I need to construct class with n template parameters (output iterators).

不,你不知道。您实际上可以创建一个具有 0 个模板参数的类。但是,每个方法本身都有一个模板参数。在你的情况下,你可以将它减少到类的 2 个模板参数:

template<class TNode, class TEdge>
class APathCalculation
{
using TGraph = AGraph<TNode, TEdge>;
public:
template<class OutputOfFunc1>
void ReturnShortestPath(size_t source, size_t dest, TGraph& graph, OutputOfFunc1 outPath);

template<class OutputOfFunc2>
void ReturnAllShortestDistances(size_t source, TGraph& graph, OutputOfFunc2 outDistances);
};

请注意,我在这里做了一个重要的更改:这是一个 OO 意义上的类。您拥有的是一个抽象 类或接口(interface)。抽象类是解耦调用者和被调用者的好方法,但在这里您不能解耦它们:调用者和被调用者必须就迭代器类型达成一致。

关于c++ - 避免在模板参数中积累迭代器类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53432489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com