9

Is it possible to emulate something like this:

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

The main goal is to be able to write code like this (in pseudo-c++):

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

f(boost::bind(a_, b_));
iammilind
  • 68,093
  • 33
  • 169
  • 336
abyss.7
  • 13,882
  • 11
  • 56
  • 100

4 Answers4

3

Your question is not technically precise. A signature is not something you pass as argument. I try my best to make sense of your question.

The following function objects can be passed as argument to each other

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

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

foo f; bar b;
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
2

Not directly possible with typedefs; wherever a typedef is used, it is equivalent to the original type, so if you write

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

then B would be equivalent to boost::function<void(A)>, which is equivalent to boost::function<void(boost::function<void(B)>)>, and so on, until you get

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

, which is a type of infinite length.

You can, however, define (at least) one of the two types as a struct or 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); }
};

You might need to add more constructors and/or a conversion operator to make the type behave completely "transparently", or you could just access the struct explicitly.

wolfgang
  • 4,883
  • 22
  • 27
0

Did you consider using function pointers?

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

I've made that sample code and it works. Maybe you could use it.

thim
  • 585
  • 1
  • 3
  • 16
0

I managed to achieve what you described by passing these functions to each other just as void*. Maybe it's not the nicest way, but it works (I tested it).

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;
}
ghik
  • 10,706
  • 1
  • 37
  • 50