是否可以模拟这样的事情:
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_));
是否可以模拟这样的事情:
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_));
您的问题在技术上并不精确。签名不是您作为参数传递的东西。我尽力理解你的问题。
以下函数对象可以作为参数相互传递
struct foo {
template<typename T> void operator()(T);
};
struct bar {
template<typename T> void operator()(T);
};
foo f; bar b;
不能直接使用 typedef;无论在哪里使用 typedef,它都等同于原始类型,所以如果你写
typedef boost::function<void(A)> B;
typedef boost::function<void(B)> A;
thenB
将等价于boost::function<void(A)>
, 等价于boost::function<void(boost::function<void(B)>)>
, 依此类推, 直到你得到
boost::function<void(boost::function<void(boost::function<void(...)>)>)>
,这是一种无限长的类型。
但是,您可以(至少)将两种类型中的一种定义为 astruct
或class
:
struct A;
typedef boost::function<void(A)> B;
struct A
{
B b;
A(B b) : b(b) {}
// optional:
void operator() (A a) { b(a); }
};
您可能需要添加更多构造函数和/或转换运算符以使该类型的行为完全“透明”,或者您可以显式访问该结构。
你考虑过使用函数指针吗?
#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);
}
我已经制作了该示例代码并且它可以工作。也许你可以使用它。
我设法通过将这些函数相互传递来实现你所描述的,就像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;
}