vendredi 30 septembre 2022

Storing pointer to functions in a map

Can anyone explain why this piece of code is generating the error as shown below. I am trying to store pointer to function in a map. The code would work fine if I keep everything in main() function. Also I would appreciate it if someone shows how to fix it.

#include <boost/variant.hpp>
#include <map>
#include <iostream>
#include <map>
using namespace boost;
class obj {
public:
    int num1;
    int num2;
    std::string s1;
    std::string s2;
};
typedef boost::variant<int, float, double, std::string> MultiType;
typedef MultiType(*FnPtr)(obj);

        
        
class c {
public:
    MultiType add(obj o);
    std::map<std::string, FnPtr> metricToFuncMap = { { "i", add } };
};
MultiType c::add(obj o) {
    { MultiType x;  x = o.num1 + o.num2; return x; }
}

int main() {
    obj o;
    //add
    MultiType d;
    d = 1;
    o.num1 = 1;
    o.num2 = 2;
    //concat
    o.s1 = "hello";
    o.s2 = "world";
    c c;
    MultiType x = c.metricToFuncMap["i"](o);
    std::cout << get<int>(x);
    return 0;
}

Error:

E0289   no instance of constructor "std::map<_Kty, _Ty, _Pr, _Alloc>::map [with _Kty=std::string, _Ty=FnPtr, _Pr=std::less<std::string>, _Alloc=std::allocator<std::pair<const std::string, FnPtr>>]" matches the argument list     

Aucun commentaire:

Enregistrer un commentaire