I have 2 similar functions, that are doing some calculations with graph nodes or edges.
void foo(const VertexMgr& mgr, const std::string name)
{
// Skipped..
for (int i = 0; i< 100; ++i)
{
// Skipped
const A& a = CreateSomething();
for (IterType<Vertex> it = a->vertices(); it != NULL(); ++it)
{
// do something
}
}
}
void goo(const EdgeMgr& mgr, const std::string& name)
{
// Skipped..
for (int i = 0; i< 100; ++i)
{
// Skipped
const A& a = CreateSomething();
for (IterType<Edge> it = a->edges(); it != NULL(); ++it)
{
// do something
}
}
}
The question is: How to get rid of the code duplication in this situation. Are there possible solution with templates?
You could use a template argument for the Vertex
/Edge
and manager object, and then std::mem_fn
for the function to call.
Wrap the actual function call to make the calling easier. Maybe something like
template<typename MgrT, typename ItrT, typename FunT>
void foo(const MgrT& mgr, const std::string& name, FunT& fn)
{
for (int i = 0; i < 100; ++i)
{
// Skipped
const A& a = CreateSomething();
for (IterType<ItrT> it = fn(a); it != NULL(); ++it)
{
// do something
}
}
}
void foo(const EdgeMgr& mgr, const std::string& name)
{
foo<EdgeMgr, Edge>(mgr, name, std::mem_fn(&A::edges));
}
void foo(const VerticeMgr& mgr, const std::string& name)
{
foo<VertexMgr, Vertex>(mgr, name, std::mem_fn(&A::vertices));
}
Not tested but it should hopefully provide a starting point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With