带有静态分派的c++ lambda

c++ lambda with static dispatch

本文关键字:c++ lambda 分派 静态      更新时间:2023-10-16

在c++中是否有一种方法可以捕获函数,将相同的名称转换为一个函数对象,可以作为静态调度的回调传递?

#include <cstdio>
using std::printf;
void foo(int a) {
    printf("foo a %dn", a);
}
void foo(float b) {
    printf("foo b %fn", b);
} 
struct A {
    int a;
    float b;
    void operator()(int a) {
        printf("A a: %dn", a+a);
    }
    void operator()(float b) {
        printf("A b: %fn", 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
}

在c++14中,可以使用泛型lambda:

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

演示

或者对于真实转发:

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

我所看到的是创建一个继承一堆lambda的模板结构体。Lambda是结构体,所以你可以在这里使用继承。

诀窍是静态地"创建"你用来获得这种行为的手动创建的结构体。

在这个问题中演示的这个可能是你想要的:https://stackoverflow.com/a/33304161/2104697

在c++中,

是一种捕获同名函数的方法一个函数对象,可以通过static作为回调传递调度?

不,不能用lambda

当编译器要为foobar生成代码时,它必须知道它的模板参数。如果仍然不明确,则编译失败。因此,您必须为operator ()编写一个具有额外重载的结构体。

您可以通过继承Guillaume Racicot提到的lambdas来简化此操作,或者您可以尝试一些宏技巧。