Reputation: 684
so I'm trying to pass a function as an argument across two classes of mine in C++:
void class1::func_1(QString str)
{
class2* r = new class2();
r->func_2(str, &process);
}
void class1::process(QString str)
{
//Do something with str
}
Where 'r->func_2' looks like the following:
QString class2::func_2(QString str, void (*callback)(QString))
{
//Do something else
}
Yet when I try to compile, I get the following errors:
must explicitly qualify name of member function when taking its address
r->func_2(str, &process);
^~~~~~~~
class1::
cannot initialize a parameter of type 'void (*)(QString)' with an rvalue of type 'void (class1::*)(QString)'
r->func_2(str, &process);
^~~~~~~~
And I can't figure out why. Any ideas? I'm clearly doing something wrong... just not sure what. Any help would be greatly appreciated. Thanks!
Upvotes: 2
Views: 7546
Reputation: 3153
The functions are member functions and they are not static. I suggest you to make use of std::function and std::bind. Through these you will be able to take functions as arguments. Just keep in mind that when you will be using std::bind to pass in the argument and it is not a static/global functions but a member of a some object, you need to also make use of this thing called placement. Look it up. You don't need to use lambdas by the way.
class A
{
std::string m_name;
void DisplayName() { std::cout << m_name };
}
void TakeFunctionAsArgument(std::function<void(void)> func)
{
func();
}
int main()
{
A objectA;
TakeFunctionAsArgument(std::bind(&A::DisplayName, objectA));
return 0;
}
Upvotes: 2
Reputation: 111
You need to fully qualify the member function name when you pass its address:
void class1::func_1(QString str)
{
class2* r = new class2();
r->func_2(str, &class1::process);
}
Upvotes: 5