Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

c++ - How do I call a member function pointer?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...