Reputation: 4716
I wanted to know what I might be doing wrong here. This is my code sample. Its just a rough code sample depicting the use of function pointers.In the following example the fuunction pointer takes in a parameter.However that parameter was already assigned during function pointer assignment.Now in order to invoke the function pointer i still need to provide a parameter value although that value is nver used (unless i used std::placeholder). My question is how do i invoke a function pointer that requires a parameter and whose parameter has already been assigned without passing in a parameter.
#include <iostream>
#include <functional>
using namespace std;
std::function<std::string(std::string)> fptr;
std::string foo()
{
return fptr(); //--->statement A - I need to invoke this funct ptr without passing a parameter as a parameter has already been assigned in statement B
}
std::string bar(std::string p)
{
return p;
}
int main()
{
fptr = std::bind(&bar,"Hello"); --->statement B
std::cout << foo();
}
Notice in std::bind
I did not use any placeholders and "Hello" is the parameter to the function bar
. My question is why does
return fptr();
not work. If i do the following
return fptr("Bye");
It works and returns "Hello" . (No point of passing parameter during fptr call) Why does it not work without a parameter ?
Upvotes: 0
Views: 43
Reputation: 1299
The result of std::bind
allows you passing more arguments than it needed, and ignore these extra arguments. In your case, std::bind(&bar, "Hello")
can be called without arguments, or, declared by fptr
, with one std::string
argument.
The solution to your problem is easy, just change the type of fptr
to std::function<std::string()>
, which accept no arguments and return a string.
Upvotes: 3