I'd like to use a pointer to member function in C++, but it doesn't work:
pointer declaration:
int (MY_NAMESPACE::Number::*parse_function)(string, int);
pointer assignation:
parse_function = &MY_NAMESPACE::Number::parse_number;
This call works perfectly (itd is an iterator to elements of a map):
printf("%s\t%p\n",itd->first.c_str(),itd->second.parse_function);
But this one doesn't work:
int ret = (itd->second.*parse_function)(str, pts);
$ error: 'parse_function' was not declared in this scope
And this one neither
int ret = (itd->second.*(MY_NAMESPACE::Number::parse_function))(str, pts);
$ [location of declaration]: error: invalid use of non-static data member 'MY_NAMESPACE::Number::parse_function'
$ [location of the call]: error: from this location
I don't understant why ...
Thx in advance !!
You can define pointers to functions like so:
type(*variable)() = &function;
For example:I might just not realize your code this early morning, but problem could be that
parse_function
is a pointer, yet you're calling it likeitd->second.*parse_function
. Pointers are called with the->*
, so try doingitd->second->parse_function
.Might not fix anything tho, I can't really seem to catch onto your code. Posting more information, it's hard to tell from two lines of code.
Here's one example on how it's used in actual code, this one calls
func()
throughcb()
using pointers and parameters only:This shows,
parse_function
is a pointer to a member function of classNumber
.printf("%s\t%p\n",itd->first.c_str(),itd->second.parse_function);
and from this we can see
parse_function
is a member ofitd->second
, whatever this is.For this call
or this call
to succeed,
itd->second
must be of typeNumber
, which it presumably isn't. And parse_function must be defined as either a variable in the current or enclosing scope (fist case) or a static variable of class Number (second case).So you need some
Number
and applyparse_function
to thator with a pointer
Update:
Since
itd->second
is a Number, you must applyparse_function
, which is a member of it, like this