C++ compile time dispatch abstraction? -
#include <iostream> struct object1 { object1(int v) : type(1), value(v) {} int type; int value; }; struct object2 { object2(int v) : type(2), value(v) {} int type; int value; }; template <typename headertype> void foo(headertype * hdr) { std::cout << "foo called type " << hdr->type << " , value " << hdr->value << std::endl; } // function doesn't work template <typename handlertype> void dispatch(int type, int val, handlertype handler) { if (type == 1) { object1 h(val); handler(&h); } else { object2 h(val); handler(&h); } } int main() { int type = 1; int val = 1; // part works if (type == 1) { object1 h(val); foo(&h); } else { object2 h(val); foo(&h); } // trying replicate above behavior in more abstract way, // ideally via function call of following sort // // dispatch(type, val, ..foo..? ); }
the above program takes input value, uses decide type of object create, calls function foo pointer object.
question: possible create sort of abstraction caller of dispatch doesn't know exact types foo called dispatch function doesn't know specific function going called?
with
template <typename handlertype> void dispatch(int type, int val, handlertype handler) { if (type == 1) { object1 h1(val); handler(&h1); } else { object2 h2(val); handler(&h2); } }
all branches should valid, handler(&h1)
, handler(&h2)
should valid calls.
for that, handler
may generic lambda (since c++14) suggested in comment:
dispatch(type, val, [](auto a) {return foo(a);} );
or may create own functor:
struct foo_caller { template <typename headertype> void operator () (const headertype* hdr) const { std::cout << "foo called type " << hdr->type << " , value " << hdr->value << std::endl; } };
and call it:
dispatch(type, val, foo_caller());
Comments
Post a Comment