I’m trying to use mem_fun_ref to send a reference to a member function of an object to another function, but I get error C2064: term does not evaluate to a function taking 0 arguments.
I didn’t reflect this in the example, but I need to send the mem_fun_ref_t to a virtual function, which is why I didn’t just make Flip a function template that takes a simple function object.
#include <iostream>
#include <string>
#include <functional>
class Coin
{
public:
Coin() {}
std::string Flip ()
{
srand(23);
int side = rand() % 2 + 1;
std::string result = "";
if (side == 1)
result = "heads.";
else
result = "tails.";
return result;
}
};
std::string Flip(std::mem_fun_ref_t<std::string, Coin> flip)
{
return flip();
}
int main()
{
std::cout << "Flipping a coin..." << std::endl;
std::string output = Flip(std::mem_fun_ref<std::string, Coin>(&Coin::Flip));
std::cout << "The coin came up " << output << std::endl;
return 0;
}
You should read up on static member functions, as well as member function pointers. There are three ways you can fix your problem.
First is to make
Coin::Flipa static member function:If
Coin::Flipneeds to be a non-static member function, you can pass aCoininstance toFlip, along with the member function pointer:Finally, if the
Flipperfunctor can be a member function from any kind of object (not only Coin), and you don’t want theFlipfree function to be a template, you’ll needstd::functionandstd::bindthat are part of the recent C++11 standard.std::functionis a general-purpose polymorphic function wrapper that works with any kind of callable target: free functions, member functions, function objects, etc. If you can’t use C++11, the Boost library has the equivalentsboost::functionandboost::bind.