【问题标题】:How to construct objects through pointer to function using map如何使用映射通过指向函数的指针构造对象
【发布时间】:2015-11-06 10:39:23
【问题描述】:

基类

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

【问题讨论】:

  • 你添加了“#include ”行吗?

标签: c++ dictionary function-pointers


【解决方案1】:

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

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

我已经用这个更正检查了你的代码,它编译正常。 code is here

UPD:另外,我可以建议您使用 std::function 而不是原始函数指针作为更类型安全的替代方案

【讨论】:

    猜你喜欢
    • 2018-02-20
    • 2013-03-07
    • 1970-01-01
    • 2010-10-31
    • 2016-09-06
    • 2023-03-31
    • 2019-03-29
    • 1970-01-01
    • 2020-06-15
    相关资源
    最近更新 更多