如何使用map通过指向函数的指针构造对象

How to construct objects through pointer to function using map

基地class

class Io_obj
{
public:
    virtual Io_obj* clone() const =0;
    virtual ~Io_obj(){}
};

派生 classes

class Io_circle : public Io_obj
{
    string c;
public:
    Io_circle(string& s):c{s}{cout << c << '\n';}
    Io_circle* clone() const override{return new Io_circle{*this};}
    static Io_obj* new_circle(string& s){return new Io_circle{s};}
};

class Io_triangle : public Io_obj
{
    string t;
public:
    Io_triangle(string& s):t{s}{cout << t << '\n';}
    Io_triangle* clone() const override{return new Io_triangle{*this};}
    static Io_obj* new_triangle(string& s){return new Io_triangle{s};}
};

主要功能

using Pf = Io_obj*(string&);
map<string,Pf> io_map{{"circle",&Io_circle::new_circle},{"triangle",&Io_triangle::new_triangle}};
vector<string> vs{"circle","triangle"};

Io_obj* get_obj(int i){
    string word = vs[i];

    if(auto f=io_map[word]){
        return f(word);
    }else{
        throw runtime_error{"shape not found"};
    }
}

我收到一个错误 couldn't deduce template parameter '_InputIterator' map<string,Pf> io_map{{"circle",&Io_circle::new_circle},{"triangle",&Io_triangle::new_triangle}};

来自 C++ 编程语言的代码 -- Bjarne Stroustrup Ch22.2.4

我也尝试了书中介绍的技巧

io_map["circle"] = &Io_circle::new_circle;
io_map["triangle"] = &Io_triangle::new_triangle;

也不行[map] does not name a type

问题是您的函数指针声明无效。好的必须如下所示:

using Pf = Io_obj*(*)(string&);

我已通过此更正检查了您的代码,并且编译正常。 code is here

UPD:此外,我建议您使用 std::function 而不是原始函数指针作为更安全的替代方法