1

I'm attempting to use a map to store functions to be called at certain times.

typedef std::function<void(rapidjson::Document&)> Callback;

std::map<std::string, Callback> _callbackDict = {
    { "foo", HandleFoo },
    { "bar", HandleBar },
};

When I attempt to store them it leads to an error:

error: could not convert '{{"foo", ((FooBar*)this)->FooBar::HandleFoo}, {"bar", ((FooBar*)this)->FooBar::HandleBar}}' from '<brace-enclosed initializer list>' to 'std::map<std::__cxx11::basic_string<char>, std::function<void(int, int)> >'

MCVE

#pragma once
#include <map>
#include <iostream>
#include <functional>

typedef std::function<void(int, int)> Callback;
class FooBar
{
private:
    std::map<std::string, Callback> _callbackDict = {
        { "foo", HandleFoo },
        { "bar", HandleBar },
    };
public:
    FooBar();
    void HandleFoo(int a, int b);
    void HandleBar(int a, int b);
    ~FooBar();

};
J. Doe
  • 97
  • 2
  • 6

2 Answers2

3

The following code compiles:

namespace rapidjson { struct Document; }

void HandleFoo(rapidjson::Document&) {}
void HandleBar(rapidjson::Document&) {}    

typedef std::function<void(rapidjson::Document&)> Callback;
std::map<std::string, Callback> _callbackDict = {
    { "foo", HandleFoo },
    { "bar", HandleBar },
};

Note that FooBar::Run() isn't relevant to your problem and doesn't need to be included in your question.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Ðаn
  • 10,934
  • 11
  • 59
  • 95
  • 1
    It's questionable if it's a good idea to answer low quality and incomplete questions, since that may just encourage more of these. – πάντα ῥεῖ Feb 13 '17 at 17:43
  • @Dan It's a grey area, and you should be absolutely sure the OP contains enough information to answer precisely. Asking for a [MCVE] in the answer is an indication, that answering was too early. – πάντα ῥεῖ Feb 13 '17 at 18:11
-1

It's still not clear exactly what you're trying to do. The smallest change to get your code to compile was already given in a comment; make your functions static:

namespace rapidjson {   struct Document; }

typedef std::function<void(int, int)> Callback;
class FooBar
{
    std::map<std::string, Callback> _callbackDict = {
        { "foo", HandleFoo },
        { "bar", HandleBar },
    };
public:
    static void HandleFoo(int a, int b);
    static void HandleBar(int a, int b);
};

But you really need to get a good C++ book and read it; this is supposed to be a Q-and-A site, not help-me-with-my-code.

Community
  • 1
  • 1
Ðаn
  • 10,934
  • 11
  • 59
  • 95