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

标签 c++ dictionary function-pointers

基类

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

派生类

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 而不是原始函数指针作为更安全的替代方法

关于c++ - 如何使用map通过指向函数的指针构造对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33564908/

相关文章:

C#-选择另一个字典中不存在的键和值

c++ - 在运行时删除持有 pthread 的变量

java - 按值对映射进行排序

C编程。为什么函数指针会破坏优化

opengl - 用作字典键,不可散列类型

c++ - 保存和加载函数指针到文件

c++ - boost multi_index_container 更改键 -> 容器状态不正确

c++ - multiset如何存储重复元素?

c++ - 忽略模板特化并显式使用非特化模板 (std::vector<bool>)

c++ - 从派生**转换为基础**