简体   繁体   中英

Substitute for function wrappers

I have a C++ class that manages two connections (source and target). Every operation on the connection is two phased, a prepare phase and a commit phase. Some of the operations I would like to do on both connections and using almost the same parameters.

Ie,

mngr::init_conn(int var1, int var2, int var3)
{
    m_conn.prepare_init(source_id, var1, var2, var3);
    m_conn.commit();

    m_conn.prepare_init(target_id, var1, var2, var3);
    m_conn.commit();
}

mngr::update_conn(int var1, int var2)
{
    m_conn.prepare_update(source_id, var1, var2);
    m_conn.commit();

    m_conn.prepare_update(target_id, var1, var2);
    m_conn.commit();
}

Notice the same connection object manages both source and target connections. The connection object is not mine, and I am not allowed to change it.

Is there a way to remove the code duplication inside the methods? I thought about wrapping the methods, but I was wondering if there is a way without generating a function wrapper for every function

I thought about something like this:

mngr::init_wrapper(ID id,int var1, int var2, int var3)
{
    m_conn.prepare_init(id, var1, var2, var3);
    m_conn.commit();
}

mngr::update_wrapper(ID id,int var1, int var2)
{
    m_conn.prepare_update(id, var1, var2);
    m_conn.commit();
}

mngr::init_conn(int var1, int var2, int var3)
{
    init_wrapper(source_id, var1, var2, var3);
    init_wrapper(target_id, var1, var2, var3);
}

mngr::update_conn(int var1, int var2)
{
    update_wrapper(source_id, var1, var2);
    update_wrapper(target_id, var1, var2);
}

Do you have ideas of ways not generating a function wrapper for every function?

How about a ranged for over std::initializer_list ?

mngr::init_conn(int var1, int var2, int var3)
{
    for (auto id : {source_id, target_id})
    {
        m_conn.prepare_init(id, var1, var2, var3);
        m_conn.commit();
    }
}

If you need to change the id inside of the for , it should be changed to auto &id , otherwise changes would be discarded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM