CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2004
    Posts
    429

    Question How to call a class member function via function pointer in map [C++]

    I'm trying to declare a std::map that is keyed by a char and has a function pointer as a second parameter, these functions would be a member function of my class. But for some odd reason I cannot call the functions when extracted...

    So, I have a class A as shown below, it contains a map as well as a function

    Code:
    class A
    {
    private:
    	map<char, void (A::*)(void)> mapA;
    public:
    	void func();
    Next I have main code that looks like this:
    Code:
    A::A()	// constructor
    {
    	// Generate User Options
    	mapA['a'] = &A::func;
    }
    Now, I try to execute func by extracting it from the map and running the function:
    Code:
    	map<char, void (A::*)(void)>::iterator it;
    	for ( it=mapA.begin() ; it != mapA.end(); it++ )
    	{
    		(*it).second();
    	}
    I would assume this would launch function "func" as it is stored in the map, but instead it generates the following error message:
    error C2064: term does not evaluate to a function taking 0 arguments

    Any help would be greatly appreciated...
    Thanks,

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: How to call a class member function via function pointer in map [C++]

    Any non-static class method takes an implicit "this" pointer representing the object upon which it operates. Thus it will not precisely match the expected function signature.

    I would suggest changing your map's value type to be a functor object which calls the desired method of the specified object upon invocation of its operator(). Functors are generally easier to deal with than raw function pointers in C++.

  3. #3
    Join Date
    Oct 2004
    Posts
    429

    Re: How to call a class member function via function pointer in map [C++]

    I'm not 100&#37; sure I understand what you mean ... functor object to call the desired method?
    Can you provide an example?
    Last edited by Shaitan00; July 6th, 2009 at 12:31 AM.

  4. #4
    Join Date
    Nov 2008
    Location
    OK, US
    Posts
    63

    Re: How to call a class member function via function pointer in map [C++]

    You can view an example of function pointer from my post here:
    http://www.codeguru.com/forum/showth...=479143&page=3

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured