Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...