0

I am trying to initialise an (unordered) map in my .hpp header file that has integer keys and member function pointer values:

// in Test.hpp
#include <unordered_map>

class Test {
private:
     std::unordered_map<int, void(*)()> tst = { 
       {1, foo}
     };

     void foo();
};

Compilation gives

test.hpp:10:2: error: could not convert ‘{{1, ((Test*)this)->Test::foo}}’ from ‘<brace-enclosed initializer list>’ to ‘std::unordered_map<int, void (*)()>’
  };
  ^

How should I alter this or is such an initialisation not possible in the header file?

Lh Lee
  • 163
  • 6
  • 5
    `void(*)()` is not a member function pointer. It's a function pointer. – François Andrieux Oct 19 '18 at 18:53
  • 2
    Pointers to _member_ functions are very different from pointers to functions, due to the implicit `this` object on which they are invoked. See this question: https://stackoverflow.com/questions/2402579/function-pointer-to-member-function – alter_igel Oct 19 '18 at 18:54

1 Answers1

0

As mentioned in comments, member function pointers are different from free function pointers. A member function pointer would be void(Test::*)();.

#include <unordered_map>

struct Test {
    using mem_fun_ptr = void(Test::*)();
     std::unordered_map<int,mem_fun_ptr> tst {  std::make_pair(1, &Test::foo) };
     void foo() {}
};

int main() {
    Test t;
}

How should I alter this or is such an initialisation not possible in the header file?

Initialization of member functions that are not static const is only allowed since C++11.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185