Reputation: 191
I have two classes. First class do some thing and then just call method of second class. Every method of first class do that. Is it possible to automate code implementation using some macro?
Example:
class A
{
void Do1()
{
Do task x
ClassB b;
b.Do1();
Do task y
}
void Do2()
{
Do task x
ClassB b;
b.Do2();
Do task y
}
}
Is it possible to implement this way? This doesn't work, but something similar.
#define VOID_FUNC(name) \
Do task x;\
ClassB b;\
b.##name##();\
Do task y;
class A
{
void Do1()
{
VOID_FUNC(__FUNCTION__);
}
void Do2()
{
VOID_FUNC(__FUNCTION__);
}
}
Upvotes: 2
Views: 1019
Reputation: 754
There are many good reasons to avoid macros, for one they don't respect namespaces.
Another solution is to use lambda functions (C++11 and later) when you want to reuse task x
and task y
:
class A
{
template <typename Fun>
void wrapClassB(Fun&& fun)
{
Do task x
ClassB b;
fun(b);
Do task y
}
void Do1()
{
wrapClassB([] (ClassB& b) {
b.Do1();
});
}
void Do2()
{
wrapClassB([] (ClassB& b) {
b.Do2();
});
}
};
For pre-C++11 you can create functors instead of lambdas and replace Fun&&
with const Fun&
.
Alternatively, if you really want to use macros, you could just define the whole function with the macro:
#define VOID_FUNC(name) \
void name() {\
Do task x;\
ClassB b;\
b.name();\
Do task y;\
}
class A
{
VOID_FUNC(Do1)
VOID_FUNC(Do2)
};
Upvotes: 2