I am trying to call a function pointer using an explicit dereference. But the compiler throws an error:
no operator "*" matches these operands.
Here's a simplified version of my code:
#include <functional>
#include <iostream>
int add(int a, int b)
{
return a + b;
}
std::function<int(int, int)> passFunction()
{
return &add;
}
int main()
{
int a{ 1 };
int b{ 2 };
std::cout << (*passFunction())(a, b);
return 0;
}
The thing is, it works fine when I just write:
std::cout << passFunction()(a, b); // without asterix.
which blows my mind.
I thought that, I messed up parentheses in function call. I tried different order and precedence, I called it with ampersand, and still compiler doesn't even flinch.
passFunctionreturns a pointer? What is the return type of that function?&addandaddare the same. But, you do not return a pointer anyway. You return astd::function<int(int, int)>which gets initialized from&add, i.e.add.&inreturn &add;caused the misconception.passFunction()(a,b);orauto fn = passFunction(); fn(a,b);Read more here en.cppreference.com/w/cpp/utility/functional/function (cppreference is the goto place for C++/standard library documentation)std::function<int(int, int)>isn't a pointer, it's an object and there's no pointer in the return type of your function.