Reputation: 3366
Base class
class Io_obj
{
public:
virtual Io_obj* clone() const =0;
virtual ~Io_obj(){}
};
Derived 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};}
};
main functions
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"};
}
}
I get an error couldn't deduce template parameter '_InputIterator'
map<string,Pf> io_map{{"circle",&Io_circle::new_circle},{"triangle",&Io_triangle::new_triangle}};
Code from the C++ programming language -- Bjarne Stroustrup Ch22.2.4
I also tried the technique presented in the book
io_map["circle"] = &Io_circle::new_circle;
io_map["triangle"] = &Io_triangle::new_triangle;
It doesn't work either [map] does not name a type
Upvotes: 0
Views: 42
Reputation: 411
the problem is your function pointer declaration is invalid. Good one must look like following:
using Pf = Io_obj*(*)(string&);
I've checked your code with this correction and it's compiled OK. code is here
UPD: Also, I can recommend you to use the std::function instead of raw function pointers as more type-safe alternative
Upvotes: 1