如何声明两个函数以彼此的签名作为参数?
How to declare two functions taking each other's signature as argument?
是否可以像这样模拟:
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 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(...)>)>)>
,这是一个无限长度的类型。
但是,您可以(至少)将这两种类型中的一种定义为struct
或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;
}
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类