Search code examples
c++c++11initializer-listpointer-to-member

using map's initializer list inside constructor initializer


Trying to create a map of int to member function pointer and initialize it inside a constructor initializer. Like this:

class X
{
    using STATEFUNC = void(X::*)(int);
public:
    X() : m{ { 1, &setState1 } } {}

    void setState1(int x) { cout << "state1" << endl; }

    void setState2(int x) { cout << "state2" << endl; }


    std::map<int, STATEFUNC> m;
};

I would say this is correct, but Visual studio 2017 says:

Error C2664 'std::map,std::allocator>>::map(std::initializer_list>)': cannot convert argument 1 from 'initializer list' to 'std::initializer_list>'

Error C2276 '&': illegal operation on bound member function expression

When you remove the address of operator from the member function the first error message stays the same but the second changes to:

Error C3867 'X::setState1': non-standard syntax; use '&' to create a pointer to member

How do you initialize a map of int to member function pointer inside a constructor initializer list?


Solution

  • Try with

    X() : m{ { 1, &X::setState1 } } {}
    

    Using only &setState1 I get, from g++, the following message error

    error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say ‘&X::setState1’ [-fpermissive]

    From clang++ the error is simply

    error: must explicitly qualify name of member function when taking its address

    -- EDIT --

    My answer explain how to solve the problem.

    To understand why &X::setState1 works and &setState1 doesn't, please see the StoryTeller's answer (+1)