vendredi 30 janvier 2015

How to store an argument to std::function , so that it can be used when called

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

Aucun commentaire:

Enregistrer un commentaire