I’m trying to learn c++ from the basics, and I was playing around with function pointers. Considering this code:
#include <iostream>
#include <string>
#include <vector>
bool print(std::string);
bool print(std::string a)
{
std::cout << a << std::endl;
return true;
}
bool call_user_function(bool(std::string), std::vector<std::string>);
bool call_user_function(bool(*p)(std::string), std::vector<std::string> args) {
if (args.size() == 0)
return (*p)(); (*)
else if (args.size() == 1)
return (*p)(args[0]);
else if (args.size() == 2)
return (*p)(args[0], args[1]); (**)
}
int main(int argc, char** argv)
{
std::vector<std::string> a;
a[0] = "test";
call_user_function(print, a);
// ok
return 0;
}
It gives me:
main.cpp:28 (*): error: too few arguments to function
main.cpp:32 (**): error: too many arguments to function
What am I doing wrong?
pis of typebool(*)(std::string). This means it is a pointer to a function that has a single parameter of typestd::stringand returns abool.pcan point toprint, because the type ofprintmatches: it is a function that has a single parameter of typestd::stringand returns abool.Your first erroneous expression,
(*p)(), attempts to callpwith no arguments. Your second erroneous expression,(*p)(args[0], args[1])attempts to callpwith two arguments.The number of arguments must match the number of parameters, so both of these are ill-formed, just like an attempt to call
printdirectly with no arguments or with two arguments would result in a compilation error.