2011-12-13 25 views
9

是否有可能效仿這樣的事情:如何聲明兩個函數將對方的簽名作爲參數?

typedef boost::function<void(A)> B; 
typedef boost::function<void(B)> A; 

主要目標是能夠寫出這樣的代碼(僞C++):

void a_(B b) { 
    // ... 
    b(a_); 
} 
void b_(A a) { 
    // ... 
    f(boost::bind(a, b_)); 
} 

f(boost::bind(a_, b_)); 

回答

2

不可能直接使用typedefs;無論是使用typedef,它是相當於原始類型,因此,如果你寫

typedef boost::function<void(A)> B; 
typedef boost::function<void(B)> A; 

然後B將相當於boost::function<void(A)>, 這相當於boost::function<void(boost::function<void(B)>)>,依此類推,直到你得到

boost::function<void(boost::function<void(boost::function<void(...)>)>)> 

,這是一種無限長度。

你可以,但是,定義(至少)兩種類型之一爲structclass

struct A; 
typedef boost::function<void(A)> B; 
struct A 
{ 
    B b; 
    A(B b) : b(b) {} 

    // optional: 
    void operator() (A a) { b(a); } 
}; 

您可能需要添加更多的構造器和/或轉換操作符使類型的行爲完全「透明」,或者你可以直接訪問結構。

0

你考慮使用函數指針?

#include <iostream> 

    // void (*functionPtr)() <- declaration of function pointer 
void f(void (*functionPtr)()) { 
    // execute the function that functionPtr points to 
    (*functionPtr)(); 
} 

void a() { 
    std::cout << "Function a()" << std::endl; 
} 

int main() { 
    f(a); 
} 

我已經提出了示例代碼,它的工作原理。也許你可以使用它。

3

你的問題在技術上並不精確。簽名不是你傳遞的參數。我盡我所能來理解你的問題。

下面的函數對象可以作爲參數傳遞給對方

struct foo { 
    template<typename T> void operator()(T); 
}; 

struct bar { 
    template<typename T> void operator()(T); 
}; 

foo f; bar b; 
0

我成功地實現您通過將這些功能彼此就像void*描述了。也許這不是最好的方式,但它有效(我測試了它)。

typedef void (*A)(void*); 
typedef void (*B)(void*); 

void afun(void* _bf) { 
    B _bfun = (B)_bf; 
    _bfun((void*)afun); 
} 

void bfun(void* _af) { 
    A _afun = (A)_af; 
    f(boost::bind(_afun, (void*)bfun)); 
} 

int main(int argc, char** argv) { 
    f(boost::bind(afun, (void*)bfun)); 
    return 0; 
} 
相關問題