1
Menu::Menu( map < string, void(*)() > options) :
    menuOptions(options)
{}

Menu Option delcaration in the Menu.h: private: // Brief: Map of a string (which describes the option) and the linking function to call map < string, void(*)() > menuOptions;

void Menu::printInvalidEntryErrorMessage() {
    cout << INVALID_ENTRY_ERROR_MESSAGE << endl; 
}

int Menu::startMenu() {
    pair<string, void(*)()> newPair = { "randomString", Menu::printInvalidEntryErrorMessage };
    menuOptions.insert(newPair);
}

Getting an error when trying to insert into this map that is member of the Menu Class. The error I get when trying to compile the code is the following:

no instance of constructor "std::pair<_Ty1, _Ty2">::pair [with _Ty1=std::string, _Ty2=void(*)()]" matches the argument list

All I am asking is how do you insert a member function into a map within a class?

Any help would be appreciated. Thank you :)

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
Noodlelynx
  • 15
  • 1
  • 8
  • A member function is a bit more complicated than just `void(*)()`, I can't really remember the syntax for pointer-to-member-functions but you could try using `std::function` – Alex Díaz Feb 27 '17 at 14:34
  • 1
    `Menu::printInvalidEntryErrorMessage` is a member function. Cannot be pointed to by function pointer. [Click](https://isocpp.org/wiki/faq/pointers-to-members) – mpiatek Feb 27 '17 at 14:35
  • 4
    The syntax for a pointer to member function is: `void(Menu::*)()` – πάντα ῥεῖ Feb 27 '17 at 14:35
  • @mpiatek Of course you can declare a function pointer for a (non static) . member function. See my comment above. – πάντα ῥεῖ Feb 27 '17 at 14:37
  • @πάνταῥεῖ What I meant was: cannot be pointed to by pointer to regular function. It needs pointer-to-member-function – mpiatek Feb 27 '17 at 14:38

1 Answers1

2

The type of &Menu::printInvalidEntryErrorMessage is not void(*)(), but actually void(Menu::*)(). You should contain that in your map:

using function_t = void(Menu::*)();
std::map<std::string, function_t> menuOption;

You can insert to your map like this (it's actually faster!):

menuOption.emplace("Keeran", &Menu::printInvalidEntryErrorMessage);

The reason for that is this: you need to pass the instance to your member function. A pointer to member function is used like that:

auto func = &Menu::printInvalidEntryErrorMessage;
(this->*func)(); // call to function.
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141