1

is there in c++ a way to capture functions witch the same name into one function object that can be passed as a callback with static dispatch?

#include <cstdio>
using std::printf;

void foo(int a) {
    printf("foo a %d\n", a);
}

void foo(float b) {
    printf("foo b %f\n", b);
} 

struct A {
    int a;
    float b;
    void operator()(int a) {
        printf("A a: %d\n", a+a);
    }
    void operator()(float b) {
        printf("A b: %f\n", b*b);
    } 
};

template <typename Func>
void foobar(Func func) {
    // static dispatch
    func(3);  
    func(2.125f);
}

int main() {
    int a = 123;
    float b = 1.23f;
    foobar(A{a,b}); // this is ok, but I have to write that struct manually
    foobar(foo); // ERROR could not infer tempate argument, but this is what I want.
    foobar([](int   a){ printf("λa "); foo(a); }
             (float b){ printf("λb "); foo(b); }); 
    // ERROR fictional syntax that doesn't exist
}
Arne
  • 7,921
  • 9
  • 48
  • 66

3 Answers3

3

In c++14, you may use generic lambda:

foobar([](auto as){ foo(as); });

Demo

Or for a real forwarding:

foobar([](auto&&... as) { foo(decltype(as)(as)...); });

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • does this also work for variable number of arguments? For a fixed number of arguments, this is pretty much perfect. – Arne Oct 27 '15 at 15:59
  • @Arne: yes, `foobar([](auto... as){ foo(as...); });` or the one from *Piotr Skotnicki* for a true forwarding. – Jarod42 Oct 27 '15 at 17:19
  • thanks for the great demo. I would also add the demo code here in the answer, because you never know how long the other host may be online. – Arne Oct 27 '15 at 23:33
  • @Arne: it is mostly the same code as in your question, so no real gain. The advantage of the link is that it shows that it works. – Jarod42 Oct 28 '15 at 08:14
0

What I've seen is to create a template struct that inherits a bunch of lambda. Lambda are structs so you can use inheritance here.

The trick will be to statically "create" the manually created struct you used to get this behaviour.

This one demonstated in this question may be what you want: https://stackoverflow.com/a/33304161/2104697

Community
  • 1
  • 1
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
0

is there in c++ a way to capture functions witch the same name into one function object that can be passed as a callback with static dispatch?

No, not with lambdas.

When the compiler is to generate code for foobar, it has to know it's template arguments. If it is still ambiguous, the compilation fails. Therefore you have to make a struct that has additional overloads for operator (), by writing your own.

You can make that easier by inheriting from lambdas as mention by Guillaume Racicot, or you can try some macro-tricks.