Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid code duplication issue in this case?

Tags:

c++

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?

like image 245
Narek Atayan Avatar asked Oct 23 '15 06:10

Narek Atayan


1 Answers

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.

like image 162
Some programmer dude Avatar answered Nov 03 '22 01:11

Some programmer dude