mardi 5 mai 2015

How to implement a polymorphic function within member function in C++11?

I am using a framework written by others. The framework use some ugly macros. Firstly, the framework use macro to declare and define class like below:

#define DECLARE_FUNC(_name, _params) \
class _name                          \
{                                    \
    static int execute();            \
    static int exec_func(_params* param);          \
}

#define DEFINE_FUNC(_name, _params)  \
int _name::execute()                 \
{                                    \
    _params p = get_from_global();   \
    return exec_func(&p)             \
}                                    \
int _name::exec_func(_param* param)

when using this framework what I have to do is:

DECLARE_FUNC(foo, database)

DEFINE_FUNC(foo, database)
{
    // write business logic here        
}

when write the business logic, I have to query information from different table in database and do almost the same thing with query result. The pseudocode is like this:

TypeA a = database.query(t_TypeA);
if (a.is_valid()) {
   // do something with a here
   // some local variables are needed
}

TypeB b = database.query(t_TypeB);
if (b.is_valid()) {
   // do something with b here
   // some local variables are needed
}

Obviously there are too many duplicate codes, which is bad. So my colleague use macro to remove the duplicate codes. I think polymorphic lambda should work in this case, but C++11 doesn't support polymorphic lambda.

My question: is there any other ways to remove the duplicate code without macro?

Aucun commentaire:

Enregistrer un commentaire