Search code examples
c++c++11stdbind

Storing the result of a bind with placeholders in a std::function


I have been reading up on, how to perform a std::bind on a regular function. And store the free function or member function into a std::function. However, if I try to use a placeholder for one argument and an actual value for the other argument; I am not able to make a call(causes compilation error) to the std::function

So I tried the following code:

#include <random>
#include <iostream>
#include <memory>
#include <functional> 

int g(int n1, int n2)
{
    return n1+n2;
}


int main()
{
    using namespace std::placeholders;  // for _1, _2, _3...

    std::function<int(int,int)> f3 = std::bind(&g, std::placeholders::_1, 4);
    std::cout << f3(1) << '\n';

//this works just fine
    auto f4 = std::bind(&g, std::placeholders::_1, 4);
    std::cout << f4(1) << '\n';
}

I get the following error g++ 4.7

prog.cpp: In function 'int main()':
prog.cpp:17:22: error: no match for call to '(std::function<int(int, int)>)         (int)'
     std::cout << f3(1) << '\n';
                  ^
In file included from /usr/include/c++/4.9/memory:79:0,
                 from prog.cpp:3:
/usr/include/c++/4.9/functional:2142:11: note: candidate is:
     class function<_Res(_ArgTypes...)>
       ^
/usr/include/c++/4.9/functional:2434:5: note: _Res         std::function<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) const [with _Res =         int; _ArgTypes = {int, int}]
     function<_Res(_ArgTypes...)>::
     ^
/usr/include/c++/4.9/functional:2434:5: note:   candidate expects 2 arguments, 1 provided

Solution

  • If you're binding an argument to the function int g(int, int), what remains as a callable is a function taking one int as an argument, not two.

    Try this:

    std::function<int(int)> f3 = std::bind(&g, std::placeholders::_1, 4);