You can defer the function call by using std::bind
:
using namespace std;
int getInt() {
cout << "getInt!" << endl;
return 42;
}
function<int(void)> foo = &getInt;
int magicNumber = 13;
cout << "before delayed definition" << endl;
function<int(void)> delayed = std::bind(plus<int>(), magicNumber, bind(foo));
cout << "after delayed definition" << endl;
int i = delayed();
cout << "after delayed call" << endl;
Output:
before delayed definition
after delayed definition
getInt!
after delayed call
You do not need to define foo
like you did, either. You can just bind getInt
directly in the definition of delayed
:
function<int(void)> delayed = bind(plus<int>(), magicNumber, bind(getInt));
For more details on std::bind, check N3797, paragraph 20.9.9.
For a more concrete explanation, cppreference says:
std::bind return type
...
Member function operator() Given an object g obtained from an earlier call to bind, when it is invoked in a function call expression g(u1, u2, ... uM), an invocation of the stored object of type std::decay::type takes place, with arguments defined as follows:
...
- If std::is_bind_expression::value == true (i.e. another bind subexpression was used as an argument in the initial call to bind), then that bind subexpression is invoked immediately and its result is passed to the invocable object. If the bind subexpression has any placeholder arguments, they are picked from u1, u2, ....
...