I've applied solutions based on some search made, but the problem still there. Thank you so much for the help.
error: must use '.*' or '->*' to call pointer-to-member function ...
source code:
#include <stdio.h>
class A
{
public:
struct data;
typedef int (A::*func_t)(data *);
typedef struct data
{
int i;
func_t func;
}
data;
data d;
void process()
{
d.func(&d);
}
A()
{
d.i = 999;
d.func = &A::print;
}
int print(data *d)
{
printf("%d\n", d->i);
return 0;
}
};
int main()
{
A *a = new A;
a->process();
return 0;
}
d.func(&d);
is not enough. func is a member-function-pointer which is pointing to a non-static member of A. So it can be invoked on an object of A. So you need to write this:
(this->*(d.func))(&d);
That would work as long as you write this inside A.
If you want to execute func from outside, say in main(), then the syntax is this:
A a;
(a.*(a.d.func))(&a.d);
That is an ugly syntax.
Your process function attempts to call d.func but it is a pointer to member function. A pointer to member function must be called on some object. Presumably you want the instance of A to be this, in which case your process function should look like:
void process()
{
(this->*(d.func))(&d);
}
Note the use of the ->* operator to call a member function when you have a pointer to it.
Other answers have already said you need to say (this->*d.func)(&d) to call a pointer-to-member function (because you need to provide the object that it's a member of)
Another option is to make the function a static function, which doesn't need special syntax to call. To do that, change the typedef like so:
typedef int (*func_t)(data *);
Then make the print function static:
static int print(data *d)
{
...
}
Now you can just call d.func(&d)
Unfortunately what you are trying to do will not be possible, the reason being that print is not a static member function. This means it expects an implicit first argument that is the this pointer.
I suggest you try using the std::function and std::bind function, something like this:
class A
{
struct data
{
std::function<void(const data&)> func;
int i;
};
data d;
public:
A()
{
d.func = std::bind(&A::print, *this);
d.i = 999;
}
void process()
{
d.func(d);
}
void print(const data& my_data)
{
std::cout << my_data.i << '\n';
}
};
Of course, since the print function now have a proper this pointer, you no longer need to pass the data structure to it:
class A
{
struct data
{
std::function<void()> func;
int i;
};
data d;
public:
A()
{
d.func = std::bind(&A::print, *this);
d.i = 999;
}
void process()
{
d.func();
}
void print()
{
std::cout << d.i << '\n';
}
};
Calling pointer the members require the class it is a member of to be the this param.
Try:
A a;
a.*(d.func)(&d);
Related
I have a class MyClass. In it, I want to create an array of function pointer and initialize the array with the functions of another class (MemberClass).
MyClass has a pointer to MemberClass as member.
but I get this compile time error
error C2440: 'initializing' : cannot convert from 'void (__thiscall MyMemberClass::* )(void)' to 'F'
//This class has the function that I want to create a function pointer to
class MemberClass
{
private:
int myValue1;
int myValue2;
public:
int GetValue1() //I want to point to this function from a function pointer in another class
{
return myvalue1;
}
int GetValue2() //I want to point to this function from a function pointer in another class
{
return myvalue2;
}
}
//This has array of function pointer that I want to point to member function of another class
Class MyClass
{
typedef void(*F)();
private:
MemberClass* mclass;
F[] f;
Process();
}
.cpp
MyClass::MyClass()
{
f[2] = {&MemberClass::GetValue1, &MemberClass::GetValue2} //This line throws error
//error C2440: 'initializing' : cannot convert from 'void (__thiscall MyMemberClass::* )(void)' to 'F'
}
void MyClass::Processing()
{
//This is how I am hoping to use the function pointer array
F[Index]();
}
F is declared as pointer to function with no parameters returning void. But your functions return int, and are member functions of MemberClass rather than plain ordinary functions. So the type you need is
typedef int (MemberClass::*F)();
Calling it is also more interesting:
int result = (mclass->*f[index])();
Suggestion: rather than a method pointer, use C++11's functional library.
I'm butchering OP's sample code slightly to simplify the example.
MemberClass stays mostly the same. I removed the member variables because the methods are now hard-coded to return 1 and 2 to make them easy to tell apart.
#include <iostream>
#include <functional>
class MemberClass
{
public:
int GetValue1()
{
return 1;
}
int GetValue2()
{
return 2;
}
};
myClass gets a rip-up because this is where the action is.
class MyClass
{
private:
I'm using an array of std::function instead of a typedef and an array of the typedef. Note the template argument int(). This is an array of functions that takes nothing and returns an int. Magic in std::bind will provide the hidden this parameter required by methods. If the function has parameters that are not known at the time of binding, use std::placeholders to save room to them in the method's parameter list.
Since the methods are bound to their object, there is no longer any need to store MemberClass* mclass;
std::function<int()> f[2];
public:
Calling the function is simple: index the array and stick the brackets on.
int Process(int index)
{
return f[index]();
}
The constructor is either a bit trickier, or less tricky, depending on your school of thought. I'm using an initializer list because it is cleaner (to me, at anyrate) and often has performance advantages. For one thing, you can swap out the array for a std::vector or most other containers without having to change a line of code other than the variable definition.
f[0] = std::bind(&MemberClass::GetValue1, mem);
f[1] =...
inside the body of the constructor is still an option.
MyClass(MemberClass * mem):
f{std::bind(&MemberClass::GetValue1, mem),
std::bind(&MemberClass::GetValue2, mem)}
{
}
};
And a silly little bit of test code to make sure this all works. Why? Because every time you don't test code in it's simplest form you're taking an unnecessary risk. If it doesn't work small, it won't work big.
int main()
{
MemberClass c;
MyClass d(&c);
std::cout << d.Process(0) << std::endl;
std::cout << d.Process(1) << std::endl;
}
All together for one cut and paste-able block:
#include <iostream>
#include <functional>
class MemberClass
{
public:
int GetValue1()
{
return 1;
}
int GetValue2()
{
return 2;
}
};
class MyClass
{
private:
std::function<int()> f[2];
public:
int Process(int index)
{
return f[index]();
}
MyClass(MemberClass * mem):
f{std::bind(&MemberClass::GetValue1, mem),
std::bind(&MemberClass::GetValue2, mem)}
{
}
};
int main()
{
MemberClass c;
MyClass d(&c);
std::cout << d.Process(0) << std::endl;
std::cout << d.Process(1) << std::endl;
}
Alright, I think the title is sufficiently descriptive (yet confusing, sorry).
I'm reading this library: Timer1.
In the header file there is a public member pointer to a function as follows:
class TimerOne
{
public:
void (*isrCallback)(); // C-style ptr to `void(void)` function
};
There exists an instantiated object of the TimerOne class, called "Timer1".
Timer1 calls the function as follows:
Timer1.isrCallback();
How is this correct? I am familiar with calling functions via function pointers by using the dereference operator.
Ex:
(*myFunc)();
So I would have expected the above call via the object to be something more like:
(*Timer1.isrCallback)();
So, what are the acceptable options for calling functions via function pointers, as both stand-alone function pointers and members of an object?
See also:
[very useful!] Typedef function pointer?
Summary of the answer:
These are all valid and fine ways to call a function pointer:
myFuncPtr();
(*myFuncPtr)();
(**myFuncPtr)();
(***myFuncPtr)();
// etc.
(**********************************f)(); // also valid
Things you can do with a function pointer.
1: The first is calling the function via explicit dereference:
int myfunc(int n)
{
}
int (*myfptr)(int) = myfunc;
(*myfptr)(nValue); // call function myfunc(nValue) through myfptr.
2: The second way is via implicit dereference:
int myfunc(int n)
{
}
int (*myfptr)(int) = myfunc;
myfptr(nValue); // call function myfunc(nValue) through myfptr.
As you can see, the implicit dereference method looks just like a normal function call -- which is what you’d expect, since function are simply implicitly convertible to function pointers!!
In your code:
void foo()
{
cout << "hi" << endl;
}
class TimerOne
{
public:
void(*isrCallback)();
};
int main()
{
TimerOne Timer1;
Timer1.isrCallback = &foo; //Assigning the address
//Timer1.isrCallback = foo; //We could use this statement as well, it simply proves function are simply implicitly convertible to function pointers. Just like arrays decay to pointer.
Timer1.isrCallback(); //Implicit dereference
(*Timer1.isrCallback)(); //Explicit dereference
return 0;
}
You don't have to dereference a function pointer to call it. According to the standard ([expr.call]/1),
The postfix expression shall have
function type or pointer to function type.
So (*myFunc)() is valid, and so is myFunc(). In fact, (**myFunc)() is valid too, and you can dereference as many times as you want (can you figure out why?)
You asked:
Timer1 calls the function as follows:
Timer1.isrCallback();
How is this correct?
The type of Timer1.isrCallback is void (*)(). It is a pointer to a function. That's why you can use that syntax.
It is similar to using:
void foo()
{
}
void test_foo()
{
void (*fptr)() = foo;
fptr();
}
You can also use:
void test_foo()
{
void (*fptr)() = foo;
(*fptr)();
}
but the first form is equally valid.
Update, in response to comment by OP
Given the posted definition of the class you would use:
(*Timer1.isrCallback)();
To use
(Timer1.*isrCallback)();
isrCallback has to be defined as a non-member variable of whose type is a pointer to a member variable of TimerOne.
void (TimerOne::*isrCallback)();
Example:
#include <iostream>
class TimerOne
{
public:
void foo()
{
std::cout << "In TimerOne::foo();\n";
}
};
int main()
{
TimerOne Timer1;
void (TimerOne::*isrCallback)() = &TimerOne::foo;
(Timer1.*isrCallback)();
}
Output:
In TimerOne::foo();
(Test this code)
If you want to define isrCallbak as a member variable of TimerOne, you'll need to use:
#include <iostream>
class TimerOne
{
public:
void (TimerOne::*isrCallback)();
void foo()
{
std::cout << "In TimerOne::foo();\n";
}
};
int main()
{
TimerOne Timer1;
Timer1.isrCallback = &TimerOne::foo;
// A little complicated syntax.
(Timer1.*(Timer1.isrCallback))();
}
Output:
In TimerOne::foo();
(Test this code)
I'm trying to call const function inside a class, but a non-const function with the same name exists.
Note: I can't just change names.
class MyQuestion
{
void fun()
{
cout<<"a";
}
void fun()const
{
cout<<"b";
}
void call()
{
fun();//<how to call fun() const?
}
};
Option #1:
Call that function through a pointer to a const qualified type:
void call()
{
static_cast<const MyQuestion*>(this)->fun();
// ~~~~^
}
c++11:
void call()
{
const auto* that = this;
//~~^
that->fun();
}
c++17:
void call()
{
std::as_const(*this).fun();
// ~~~~~~~^
}
Option #2:
Make the calling function a const-qualified one:
void call() const
// ~~~~^
{
fun();
}
DEMO
You have to call the function on a const pointer. For this, I recommend to create a local pointer variable:
const auto *c = this;
c->fun(); // calls fun() const
fun(); // calls fun()
Live Demo
If you need that often, and/or if you don't want to use a local variable, you could also introduce a private helper function which returns a const this pointer:
const MyQuestion *const_this() const {
return this;
}
and then call fun like this:
const_this()->fun(); // calls fun() const
fun(); // calls fun()
Live Demo
Yet another option is to write a make_const function which performs a cast to a const pointer without the need to mention the class name (it's basically a static_cast to a const pointer of a deduced type):
template <typename T>
const T* make_const(T *ptr) {
return ptr;
}
and then call fun like this:
make_const(this)->fun(); // calls fun() const
fun(); // calls fun()
Live Demo
For the sake of argument (I don't recommend the following), combining with the suggestion above, you could also introduce a global macro which expands to make_const(this):
#define const_this make_const(this)
and then call fun like this:
const_this->fun(); // calls fun() const
fun(); // calls fun()
Live Demo
I would like to add another possible solution to the excelent ones already posted.
You can help the compiler to choose the correct overload using a function pointer with the expected signature:
// Pointer to the version of fun with const
void (MyQuestion::*f)()const = &MyQuestion::fun;
(this->*f)(); // This would call the const fun
See the demo here, or the full code below:
struct MyQuestion
{
void fun()
{
std::cout<<"a";
}
void fun()const
{
std::cout<<"b";
}
void call()
{
void (MyQuestion::*f)()const = &MyQuestion::fun;
(this->*f)();
}
};
Why does this work?
Well, the type of the f pointer is void (MyQuestion::*)()const which is the same of MyQuestion::foo()const but not the same of MyQuestion::foo(), so when you take te address of the function &MyQuestion::fun the pointer f could only point to the const version.
how about overloading call() itself. Following implementation does the job. I m guessing that it is what you want to implement.
#include <iostream>
using namespace std;
class A
{
public:
void fun() { cout << "non" << endl; }
void fun() const { cout << "const" << endl; }
void call() { fun(); }
void call() const { fun(); }
};
int main()
{
A a;
a.call();
const A b;
b.call();
return 0;
}
I suspect this is impossible, but thought I'd ask. Say I have a class with a method:
class A {
public:
void b(int c);
};
I can make a pointer to that member function:
void (A::*ptr)(int) = &A::b;
(someAInstance.*ptr)(123);
I can also abuse function pointers and make a pointer that takes the A argument directly (I don't know if this is safe, but it works on my machine):
void (*ptr2)(A*, int) = (void (*)(A*, int))&A::b;
(*ptr2)(&someAInstance, 123);
What I want is to somehow curry the A argument, and create a function pointer that just takes an int, but calls the A::b method on a particular A instance I've predefined. The A instance will stay constant for that particular function pointer, but there may be several function pointers all pointing to the same A::b method, but using different A instances. For example, I could make a separate wrapper function:
A* someConstantA = new A;
void wrapper(int c) {
someConstantA->b(c);
}
void (*ptr3)(int) = &wrapper;
Now I can use ptr3 without knowing which particular A it's dispatching the call to, but I had to define a special function to handle it. I need a way to make pointers for any number of A instances, so I can't hardcode it like that. Is this in any way possible?
Edit: Should've mentioned, I'm trapped in C++03 land, and also can't use Boost
Don't create a wrapper function, create a wrapper functor. This allows you to encapsulate whatever state you want to (e.g. an A*) in a callable object.
class A {
public:
void b(int c) {}
};
struct wrapper {
A* pA;
void (A::*pF)(int);
void operator()(int c) { (pA->*pF)(c); }
wrapper(A* pA, void(A::*pF)(int)) : pA(pA), pF(pF) {}
};
int main () {
A a1;
A a2;
wrapper w1(&a1, &A::b);
wrapper w2(&a2, &A::b);
w1(3);
w2(7);
}
If you have a sufficiently new compiler (e.g. gcc 4.2+), it should include TR1, where you could use std::tr1::bind:
#include <cstdio>
#include <tr1/functional>
class A {
public:
void b(int c) {
printf("%p, %d\n", (void*)this, c);
}
};
int main() {
A* a = new A;
std::tr1::function<void(int)> f =
std::tr1::bind(&A::b, a, std::tr1::placeholders::_1); // <--
f(4);
delete a;
return 0;
}
It is also doable in pure C++03 without TR1, but also much more messier:
std::binder1st<std::mem_fun1_t<void, A, int> > f =
std::bind1st(std::mem_fun(&A::b), a);
You could also write your own function objects.
Note that, in all the above cases, you need to be very careful about the lifetime of a since that is a bare pointer. With std::tr1::bind, you could at least wrap the pointer in a std::tr1::shared_ptr, so that it can live just as long as the function object.
std::tr1::shared_ptr<A> a (new A);
std::tr1::function<void(int)> f =
std::tr1::bind(&A::b, a, std::tr1::placeholders::_1);
If you are using C++11, you might use a lambda (untested code):
template<typename T, typename A>
std::function<void(A)> curry(T& object, void (T::*ptr)(A))
{
return [](A a) { (object.*ptr)(std::forward<A>(a)); }
}
I'd be using Boost::bind for this.
Basically:
class A
{
int myMethod(int x)
{
return x*x;
}
};
int main(int argc, char* argv[])
{
A test();
auto callable = boost::bind(&A::myMethod, &A, _1);
// These two lines are equivalent:
cout << "object with 5 is: " << test.myMethod(5) << endl;
cout << "callable with 5 is: " << callable(5) << endl;
return 0;
}
I think that should work. I'm also using auto in here to deduce the type returned by boost::bind() at compile-time, which your compiler may or may not support. See this other question at stackoverflow for an explanation of the return type of bind.
Boost supports back to Visual Studio 2003 (I think) and this all this will work there, though you'll be using BOOST_AUTO I think. See the other question already linked for an explanation.
What you want to do is not possible.
To see why, assume that it is possible - the function pointer must point to a function somewhere in your executable or one of its libraries, so it must point to a function that knows which instance of A to call, much like your wrapper function. Because the instance of A is not known until runtime, you'd have to create those functions at runtime, which isn't possible.
What you're trying to do is possible in C++03, as long as you're happy to pass around a function object rather than a function pointer.
As others have already given solutions with C++11 lambdas, TR1 and boost (all of which are prettier than the below), but you mentioned you can't use C++11, I'll contribute one in pure C++03:
int main()
{
void (A::*ptr)(int) = &A::b;
A someAInstance;
std::binder1st<std::mem_fun1_t<void,A,int> > fnObj =
std::bind1st(std::mem_fun(ptr), &someAInstance);
fnObj(321);
};
I've worked something out with a template Delegate class.
// T is class, R is type of return value, P is type of function parameter
template <class T, class R, class P> class Delegate
{
typedef R (T::*DelegateFn)(P);
private:
DelegateFn func;
public:
Delegate(DelegateFn func)
{
this->func = func;
}
R Invoke(T * object, P v)
{
return ((object)->*(func))(v);
}
};
class A {
private:
int factor;
public:
A(int f) { factor = f; }
int B(int v) { return v * factor; }
};
int _tmain(int argc, _TCHAR* argv[])
{
A * a1 = new A(2);
A * a2 = new A(3);
Delegate<A, int, int> mydelegate(&A::B);
// Invoke a1->B
printf("Result: %d\n", mydelegate.Invoke(a1, 555));
// Invoke a2->B
printf("Result: %d\n", mydelegate.Invoke(a2, 555));
_getch();
delete a1;
delete a2;
return 0;
}
I have a class A which contains member functions foo() and bar() which both return a pointer to class B. How can I declare an array containing the functions foo and bar as a member variable in class A? And how do I call the functions through the array?
The member function pointer syntax is ReturnType (Class::*)(ParameterTypes...), so e.g.:
typedef B* (A::*MemFuncPtr)(); // readability
MemFuncPtr mfs[] = { &A::foo, &A::bar }; // declaring and initializing the array
B* bptr1 = (pointerToA->*mfs[0])(); // call A::foo() through pointer to A
B* bptr2 = (instanceOfA.*mfs[0])(); // call A::foo() through instance of A
See e.g. this InformIT article for more details on pointers to members.
You might also want to look into Boost.Bind and Boost.Function (or their TR1 equivalents) which allow you to opaquely bind the member-function-pointers to an instance:
typedef boost::function<B* ()> BoundMemFunc;
A instanceOfA;
BoundMemFunc mfs[] = {
boost::bind(&A::foo, &instanceOfA),
boost::bind(&A::bar, &instanceOfA)
};
B* bptr = mfs[0](); // call A::foo() on instanceOfA
To use such an array as a member, note that you can't initialize arrays using the member initializer list. Thus you can either assign to it in the constructor body:
A::A {
mfs[0] = &A::foo;
}
... or you use a type that can actually be initialized there like std::vector or boost::array:
struct A {
const std::vector<MemFuncPtr> mfs;
// ...
};
namespace {
std::vector<MemFuncPtr> init_mfs() {
std::vector<MemFuncPtr> mfs;
mfs.push_back(&A::foo);
mfs.push_back(&A::bar);
return mfs;
}
}
A::A() : mfs(init_mfs()) {}
What you're looking for are pointers to member functions. Here is a short sample that shows their declaration and use:
#include <iostream>
class B {
public:
B(int foo): foo_(foo) {
std::cout << "Making a B with foo_ = " << foo_ << std::endl;
}
~B(void) {
std::cout << "Deleting a B with foo_ = " << foo_ << std::endl;
}
int foo_;
};
class A {
public:
A(void) {
funcs_[0] = &A::foo;
funcs_[1] = &A::bar;
}
B* foo(void) {
return new B(3);
}
B* bar(void) {
return new B(5);
}
// Typedef for the member function pointer, for everyone's sanity.
typedef B* (A::*BMemFun)(void);
BMemFun funcs_[2];
};
int main(int argc, char *argv[]) {
A a;
for (int i = 0; i < 2; ++i) {
A::BMemFun func = a.funcs_[i];
// Call through the member function pointer (the .* operator).
B* b = (a.*func)();
delete b;
}
return 0;
}
The C++ FAQ section on pointers to member functions is where I found all this information.
C++ that's not ancient (read: C++11 and later) makes this all easier. In modern C++, you can do
#include <vector>
class B;
class A {
public:
B* foo() {
// return something;
return nullptr;
}
B* bar() {
// return something;
return nullptr;
}
//C++ 11: functional brings std::function, which has zero overhead
//but is actually a useful type with which one can work
std::vector<std::function<B*()>> container;
/* [=]() { return foo(); }
* that's a lambda. In practice it "compiles away", i.e. calling
* the lambda function is the same as calling foo or bar directly
* Note how [=] means we're passing in "this", so that we can
* actually call foo().
*/
A() : container{{[=]() { return foo(); }}, {[=]() { return bar(); }}} {}
};
(Try on godbolt compiler explorer)
Here's a more complete example showcasing what to do with these.
An architectural remark: Be careful with pointers to non-static member functions. What happens if your instance of A gets destroyed, but you still have a function handle to a member function? Right, hell freezes over: There's no object anymore to which this method belongs, so results are catastrophic.