带有静态调度的 C++ lambda

标签 c++ lambda

在 c++ 中是否有一种方法可以将同名函数捕获到一个函数对象中,该函数对象可以通过静态调度作为回调传递?

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

最佳答案

在 c++14 中,您可以使用通用 lambda:

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

Demo

或者对于真正的转发:

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

Demo

关于带有静态调度的 C++ lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33368295/

相关文章:

c++ - 如何处理一些频繁使用的库的逐步重构?

Lambda 在初始化之前访问封闭类的最终字段

c# - LINQ 选择 Lambda 形式的非重复计数

java - 如何处理 lambda 中的已检查异常?

C# 编译器错误 : Cannot convert lambda expression

lambda - 这是什么 java8 语法?我在哪里可以阅读更多内容?

c++ - 在基类中有一个方法可以分配给子类

c++ - 手动生成 mipmap

c++ - C++ 中的蛇不会连续转两次

c++ - OpenGL 阴影平移