Assume I have an interface
class I{
public:
virtual void f(int id)=0;
virtual void g(int id, float x)=0;
}
I need a proxy class, to do some sort of id to pointer mapping
class Proxy : I
{
I * i[5];
public:
void f(int id)
{
i[id]->f(id);
}
void g(int id, float x)
{
i[id]->g(id, x);
}
}
So when i write
Proxy *p;
p->f(1);
f is called on the object with id=1
there are several such cases and interfaces are rather large. So I don't want to code all the functions in the proxy class. Is there way to do it automatically? maybe using macros, templates, overloading "->" etc.
The easy solution is to define an operator-> that returns the pointer to the interface. But this will break your encapsulation since everybody can access your objects directly and you actually don't need your proxy class (you might as well just use a std::map).
Alternative you could do something like
template <typename Interface>
class Proxy
{
Interface* interfaces[5];
public:
template <typename F, typename... Params>
auto operator()(F f, const int id, Params... parameters)
-> decltype((interfaces[id]->*f)(id, parameters...))
{ return (interfaces[id]->*f)(id, parameters...); }
};
It heavily relies on C++11 features so it might not compile with your compiler.
First it uses the Variadic templates. See https://en.wikipedia.org/wiki/Variadic_Templates for more information.
Next it uses decl_type. See https://en.wikipedia.org/wiki/Decltype for more information.
You have to use it like this:
Proxy<I> p;
...
p(&I::f,1);
p(&I::g,3, 1.);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With