【问题标题】:c++ lambda with static dispatch带有静态调度的 c++ lambda
【发布时间】:2015-10-27 12:42:18
【问题描述】:

在 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 中:foobar([](auto&amp;&amp;... as){ foo(decltype(as)(as)...); });

标签: c++ lambda


【解决方案1】:

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

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

Demo

或者对于真正的转发:

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

Demo

【讨论】:

  • 这是否也适用于可变数量的参数?对于固定数量的参数,这非常完美。
  • @Arne: 是的,foobar([](auto... as){ foo(as...); }); 或来自 Piotr Skotnicki 的那个,用于真正的转发。
  • 感谢精彩的演示。我还会在答案中添加演示代码,因为您永远不知道其他主机可能在线多长时间。
  • @Arne:它与您的问题中的代码基本相同,因此没有真正的收获。该链接的优点是它表明它有效。
【解决方案2】:

我所看到的是创建一个模板结构,它继承了一堆 lambda。 Lambda 是结构体,因此您可以在此处使用继承。

诀窍是静态“创建”用于获取此行为的手动创建的结构。

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

【讨论】:

    【解决方案3】:

    c++ 中有没有一种方法可以将同名的函数捕获到 一个可以作为带有静态回调的函数对象 派送?

    不,不是 lambdas。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-01
      • 2014-11-05
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-25
      相关资源
      最近更新 更多