假设我有一个接口(interface)
class I{
public:
virtual void f(int id)=0;
virtual void g(int id, float x)=0;
}
我需要一个代理类,来做一些 id 到指针的映射
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);
}
}
所以当我写的时候
Proxy *p;
p->f(1);
f 在 id=1 的对象上调用
这种情况有好几种,接口(interface)也比较大。 所以我不想在代理类中编写所有功能。 有没有办法自动完成?可能使用宏、模板、重载“->”等。
最佳答案
简单的解决方案是定义一个返回接口(interface)指针的运算符->。但这会破坏你的封装,因为每个人都可以直接访问你的对象,而你实际上不需要你的代理类(你也可以只使用 std::map)。
或者你可以做类似的事情
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...); }
};
它严重依赖 C++11 特性,因此它可能无法使用您的编译器进行编译。
首先,它使用 Variadic 模板。参见 https://en.wikipedia.org/wiki/Variadic_Templates获取更多信息。
接下来它使用 decl_type。参见 https://en.wikipedia.org/wiki/Decltype获取更多信息。
你必须像这样使用它:
Proxy<I> p;
...
p(&I::f,1);
p(&I::g,3, 1.);
关于c++ - 自动代理类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10228343/