问题
I am using C++11 with GNU tool chain on Ubuntu 12.04 LTS 32 bit. I know similar questions have been asked, but I haven't found exactly this one, and I wasn't able to get anything that worked from what is already posted, so here goes:
I have code like this:
enum class FUNC_TYPES { FUNCTYPE_1,FUNCTYPE_2,FUNCTYPE_3};
class AClass
{
...
typedef void (AClass::* TFunc )( );
std::map<FUNC_TYPES, TFunc> mFuncMap;
void doStuff();
....
}
I initialize mFuncMap like this:
void AClass::initFuncMap( )
{
mFuncMap[FUNC_TYPES::FUNCTYPE_1] = & AClass::doStuff;
}
All that compiles fine.
Now I want to call the mapped function pointer.
I tried this form, which I know works for function pointers that are not for member functions.
mFuncMap[FUNC_TYPES::FUNCTYPE_1]( );
This generates a very long explanatory compiler error:
error: must use ‘.’ or ‘->’ to call pointer-to-member function in (AClass*)this)->AClass::mFuncMap.std::map<_Key, _Tp, _Compare, _Alloc>...
I tried just about every form of de-referencing I can think of and that I found from searching around - with parenthesis, without them, etc. etc. etc... but I cannot get the syntax right to make this call.
What is the correct syntax for calling the mapped member function? Is there something wrong with my declaration or initialization that is causing this problem?
回答1:
This has nothing to do with maps, and nothing to do with typedefs. You have a pointer-to-member-function and you're not invoking it properly.
You need an AClass
to run the function on:
AClass& a = someAClassSomewhere();
(a.*(mFuncMap[FUNC_TYPES::FUNCTYPE_1]))();
Of course this is really ugly, so consider binding the object ahead of time:
typedef std::function<void()> TFunc;
std::map<FUNC_TYPES, TFunc> mFuncMap;
// ...
mFuncMap[FUNC_TYPES::FUNCTYPE_1] = std::bind(&AClass::doStuff, this);
// ...
mFuncMap[FUNC_TYPES::FUNCTYPE_1]();
(live demo)
来源:https://stackoverflow.com/questions/24325612/how-do-i-call-a-member-function-pointer