( ) @yuyoyuppe, --, , . , , discover_vertex examine_edge. false:
namespace details {
struct no_halting {
template <typename GraphElement, typename Graph>
bool operator()(GraphElement const&, Graph const&) {
return false;
}
};
}
.
template <typename VertexPredicate = details::no_halting,
typename EdgePredicate = details::no_halting,
typename BFSVisitor = boost::default_bfs_visitor>
struct bfs_halting_visitor : public BFSVisitor {
private:
VertexPredicate vpred;
EdgePredicate epred;
};
3 :
- ,
discover_vertex ( ) - ,
examine_edge ( ) - ,
, :
template <typename VPred, typename EPred, typename ... VisArgs>
bfs_halting_visitor(VPred&& vpred, EPred&& epred, VisArgs&&... args) :
BFSVisitor(std::forward<VisArgs>(args)...),
vpred(vpred), epred(epred) {}
() - :
template <typename Pred, typename R, typename ... FArgs, typename ... Args>
void throw_on_predicate(R (BFSVisitor::*base_fct)(FArgs...), Pred&& pred, Args&&... args) {
bool result = pred(args...);
(this->*base_fct)(std::forward<Args>(args)...);
if (result) {
throw std::runtime_error("A predicate returned true");
}
}
, std::runtime_error, , std::exception .
:
template <typename Edge, typename Graph>
void examine_edge(Edge&& e, Graph&& g) {
throw_on_predicate(&BFSVisitor::template examine_edge<Edge, Graph>, epred,
std::forward<Edge>(e), std::forward<Graph>(g));
}
template <typename Vertex, typename Graph>
void discover_vertex(Vertex&& v, Graph&& g) {
throw_on_predicate(&BFSVisitor::template discover_vertex<Vertex, Graph>, vpred,
std::forward<Vertex>(v), std::forward<Graph>(g));
}
, true N- .
struct VertexCounter {
VertexCounter(std::size_t limit) : count(0), limit(limit) {}
VertexCounter() : VertexCounter(0) {}
template <typename V, typename G>
bool operator()(V&&, G&&) {
return ((++count) > limit);
}
private:
std::size_t count;
std::size_t const limit;
};
bfs :
Graph graph = get_graph();
Vertex start_vertex;
bfs_halting_visitor<VertexCounter> vis(VertexCounter(2), details::no_halting());
try {
boost::breadth_first_search(graph, start_vertex, boost::visitor(vis));
} catch (std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
A Coliru , .