【发布时间】: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&&... as){ foo(decltype(as)(as)...); });