带有静态分派的c++ lambda
c++ lambda with static dispatch
在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来简化此操作,或者您可以尝试一些宏技巧。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 可组合的lambda/std::函数与std::可选
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 如何将lambda作为模板类的成员函数参数
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 在 lambda 捕获中声明的变量的类型推导
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 模板函数指针和lambda
- 两组使用lambda函数的大括号
- 使lambda不可复制/不可移动
- FLTK:按下哪个按钮 - 将数字传递给按钮的回调 (lambda)
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 将带有unique_ptr的可变 lambda 传递给 const&std::function
- AWS Lambda C++运行时权限被拒绝
- 捕获lambda中的std::数组
- 这 4 个 lambda 表达式之间有什么区别?
- 在实现文件中使用头文件的通用 lambda
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?