2012-04-19 66 views
7

假設我有一個接口自動代理類

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的對象上被調用

有幾個這種情況下,接口相當大。 所以我不想編寫代理類中的所有函數。 有沒有辦法自動做到這一點?也許使用宏,模板,重載「 - >」等

+0

你寫了很多接口相同的代理服務器,或者很多的代理類相同的接口,或者很多的代理有很多接口? – hansmaad 2012-04-19 13:31:02

+0

這有點令人困惑:它看起來像我和實例不知道他自己的索引,但它知道他的f或g方法何時被調用......爲什麼?奇怪的設計。我會計劃整個事情,我從不知道他自己的索引。這會更有意義。 – 2012-04-19 13:40:59

+0

@ hansmaad,很多接口的許多代理(一對一) – 2012-04-19 13:46:45

回答

4

簡單的解決方案是定義一個operator->,它返回指向接口的指針。但是這會破壞你的封裝,因爲每個人都可以直接訪問你的對象,而你實際上不需要你的代理類(你可能只需要使用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.); 
+0

woow!我們沒有一個兼容C++ 11的編譯器,但是,這很漂亮!謝謝! – 2012-04-20 15:02:57

+0

那麼你能接受答案:-) – BertR 2012-04-20 15:17:25

+0

好吧,我想這是我能得到的最好的:) – 2012-04-20 15:19:06

0

我不知道這是不是適合你,但你可以採取這種使用指針的護理功能...

即。

#include <stdio.h> 

typedef void (*f)(int); 

void f1(int a) 
{ 
    printf("f1: %d\n", a); 
} 
void f2(int a) 
{ 
    printf("f2: %d\n", a); 
} 
int main(int argc, char *argv[]) 
{ 
    f array[5] = {NULL}; // create array of pointers 
    array[0] = f1; // assign different functions on them 
    array[1] = f2; // -||- 

    array[0](10); // call them 
    array[1](12); 

    // and you end up with something like "array[i]();" in your proxy class... 
}