在C++11中,有一种std::bind
方法将给定的右值或左值引用连接到函数的参数,以在函数调用时传递给定的参数,例如:
#include <functional>
#include <iostream>
int foo(int x, int y) {
return x + y;
}
int main() {
std::function<int(void)> f = std::bind(foo, 1, 2);
std::cout << f() << std::endl;
}
我的问题是,是否有一个内置的方法将函数的结果绑定到某个变量的引用,以便能够执行以下操作:
#include <functional>
#include <iostream>
int foo(int x, int y) {
return x + y;
}
int main() {
int result;
std::function<void(int, int)> f = bind_result(foo, result);
f(1, 2);
std::cout << result << std::endl;
}
使用lambda:
int result;
auto f = [&result](int a, int b){ result = foo(a, b); };
如果你想要转发任意参数的东西,你可以使用一个可变模板:
auto fvar = [&result](auto... args) {
result = foo(std::forward<decltype(args)>(args)...);
};