4

I was wondering if there was a way that I could make a map(in C++) return a func. This is my code now and it doesn't work, I get a compiler error.

#include <map>
#include <iostream>
#include <string>
using namespace std;

map<string, void()> commands;

void method()
{
    cout << "IT WORKED!";
}

void Program::Run()
{
    commands["a"]();
}

Program::Program()
{
    commands["a"] = method;
    Run();
}

Any bit of advice would be awesome! Thank you in advance.

1
  • 7
    With C++11, std::map<std::string, std::function<void()>> Commented Oct 23, 2012 at 3:01

2 Answers 2

4

You can't store a function in a map -- only a pointer to a function. With a few other minor details cleaned up, you get something like this:

#include <map>
#include <iostream>
#include <string>

std::map<std::string, void(*)()> commands;

void method() {
    std::cout << "IT WORKED!";
}

void Run() {
    commands["a"]();
}

int main(){ 
    commands["a"] = method;
    Run();
}

At least with g++ 4.7.1, this prints IT WORKED!, as you apparently wanted/expected.

Sign up to request clarification or add additional context in comments.

Comments

2

Again typedef is your friend.

typedef void (*func)();
map<string, func> commands;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.