简体   繁体   中英

Binding function result in C++

In C++11 there is a std::bind method to connect given rvalue or lvalue references to parameters of a function to pass the given parameters while function invocation eg:

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

My question is, is there a built in method to bind the result of the function to reference of some variable to be able to do something like:

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

Use a lambda:

int result;
auto f = [&result](int a, int b){ result = foo(a, b); };

If you want something that forwards arbitrary arguments, you can use a variadic template:

auto fvar = [&result](auto... args) {
  result = foo(std::forward<decltype(args)>(args)...);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM