I have already searched a lot, but cannot figure out the the correct syntax. All I'm trying results in some syntax errors. Without a member function I can get it to compile.
Here is my sample:
class TestClass
{
public:
typedef bool (TestClass::* demoFunc)(int);
struct Container
{
Container(demoFunc func)
: func(func)
{}
demoFunc func;
};
Container* containers;
bool foo1(int dummy) { return true; }
bool foo2(int dummy) { return true; }
void InvokeFunction(int i)
{
TestClass::Container container = containers[i];
// How do I call the function here?
bool result = container.func(0); // here is the error
}
};
int main()
{
TestClass testClass;
testClass.containers = new TestClass::Container[]
{
TestClass::Container(&TestClass::foo1),
TestClass::Container(&TestClass::foo2),
};
testClass.InvokeFunction(0);
testClass.InvokeFunction(1);
}
This is the compler error:
expression preceding parentheses of apparent call must have (pointer-to-) function type
CodePudding user response:
The operator ->*
allow you to call a member function using a pointer to the instance.
The operator .*
allow you to call a member function using directly an instance or a reference to an instance.
You can use them followed by your member function address in order to make a call to that function.
e.g.
struct Test
{
bool foo(int val){ return true; }
};
int main()
{
Test test_instance;
Test* test_pointer = &test_instance;
Test& test_reference = test_instance;
auto FuncAddress = &Test::foo;
//calling foo using pointer
(test_pointer->*FuncAddress)(0);
//calling foo using directly the instance
(test_instance.*FuncAddress)(0);
//calling foo using a reference to the instance
(test_reference.*FuncAddress)(0);
return 0;
}
CodePudding user response:
Dereferencing/calling a pointer-to-member requires a target object (of type TestClass
, in this case).
Presumably you want to use this
: bool result = (this->*container.func)(0);
CodePudding user response:
Pointers_to_members syntax is not trivial, in your case, it would be:
bool result = (this->*(container.func))(0);
As alternative, std::invoke
(C 17) might be used
std::invoke(container.func, this, 0);