如何声明两个函数以彼此的签名作为参数?

How to declare two functions taking each other's signature as argument?

本文关键字:参数 函数 声明 何声明 两个      更新时间:2023-10-16

是否可以像这样模拟:

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(...)>)>)>

,这是一个无限长度的类型。

但是,您可以(至少)将这两种类型中的一种定义为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); }
};

您可能需要添加更多的构造函数和/或转换操作符,以使类型的行为完全"透明",或者您可以直接访问结构体

你考虑过使用函数指针吗?

#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;
}