1

This question answers how to do it for a regular unordered_map, but what about the member one? The IDE reports the error in the comment. opcodes maps characters to pointers to functions, which should be called on behalf of concrete instances. Also I wonder if it's possible to make it constexpr.

// Foo.cpp

class Foo {
public:
    void execute(char c) { (*opcodes[c])(); }

    void operation1()
    {
        // Do something with value_
    }

    void operation2();

private:
    typedef void (*operation)();

    static const std::unordered_map<char, operation> opcodes{
            {'1', &Foo::operation1},
            {'2', &Foo::operation2}
    }; // No matching constructor for initialization of 'const std::unordered_map<char, operation>' (aka 'const unordered_map<char, void (*)()>')
    int value_;
}
// main.cpp

int main()
{
    Foo foo;
    foo.execute('1');

    return 0;
}
1
  • Are you sure your operation type is right? Hint: pointer to function and pointer to member function are not the same type. Commented Feb 11, 2021 at 20:28

1 Answer 1

3

How to create a member unordered_map with values of pointers to functions?

Like this:

struct example {
    using fun = return_type(/*arg types*/);
    std::unordered_map<key_type, fun*> map;
};

typedef void (*operation)();
static const std::unordered_map<char, operation> opcodes{
        {'1', &Foo::operation1},
        {'2', &Foo::operation2}
}

The problem with this is that you have a map of pointers function, but you try to initialise with pointers to member functions. A pointer to member function is not a pointer to function and cannot be converted to a pointer to function.

So, what you need is a map of pointers to member functions instead:

using operation = void (Foo::*)();

Or, you need to not be using non-static member functions.


And how to call the [pointer to member] function after getting it from map?

Example:

(this->*opcodes.at('1'))();
Sign up to request clarification or add additional context in comments.

5 Comments

So the problem is that I use non-static functions in a static context, and the solution is to create an external structure which will do the mapping by itself?
@kenticent I've added two alternative solutions to the answer.
And how to call the function after getting it from map? I suspect (*opcodes.at('1'))() won't work (it doesn't).
@kenticent I added an example.
Thanks for a profound answer, figured it out just before you wrote)

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.