i spin and then i lock
i spin and then i lock

Reputation: 415

C++: How to create a member unordered_map with values of pointers to functions

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;
}

Upvotes: 1

Views: 254

Answers (1)

eerorika
eerorika

Reputation: 238311

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'))();

Upvotes: 3

Related Questions