There are two classes
AandB, each having functionsfandg(with the same signatures).The function
bool is_A(uintptr_t ptr)returns true if and only ifptrpoints to an instance ofA, and similarly foris_B.The function
A* use_A(uintptr_t ptr)convertsptrtoA*.
In the code, the following pattern is common:
answer = is_A(ptr) ? use_A(ptr)->f() : use_B(ptr)->f();
...
answer = is_A(ptr) ? use_A(ptr)->g() : use_B(ptr)->g();
Problem: is it possible to simplify this code (e.g. with a macro or a template)?
I tried the following macro:
#define call(ptr, func) (is_A(ptr) ? use_A(ptr)->func() : use_B(ptr)->func())
however I am getting "expression func cannot be used as a function".
Note: @Jarod42 and Pete Becker pointed out that this does compile. My use case turned out to be more specific than the above example. Either way, the accepted answer below solves the problem in my use case.
Note: as pointed out, this is easily and cleanly solved with virtual methods, however these tend to perform much slower in practice. I am looking for something lightweight.
std::variant<A, B>and using the visitor pattern to dispatch to the correct function usingstd::visitAandBshould derive from some base class with virtual methodsf,getc. - and then you can use a polymorphic call.