mercredi 26 août 2020

Io_obj*(istream&) as a pointer to function in Stroustrup

In The C++ Programming Language (p.650 of Fourth Edition paperback), Stroustrup writes some code for a map with a string as the key and function pointer as the mapped type (comment is his own):

using Pf = Io_obj*(istream&); // pointer to function returning an Io_obj*
std::map<std::string,Pf> io_map;

I am not really familiar with function pointers and I wanted to make my own test code where you have a string like "add 1 2", break off the first word to pass as the key to map, and pass the remainder as the argument to the calculating function pointer that map returns. My types are simpler (plain old int and plain old string) but it took me some googling to get it into a form the compiler would accept. Leaving out the alias here for simplicity:

std::map<std::string,int(std::string)> calc_map; // Stroustrup's syntax (comipile error)...

became...

std::map<std::string,int(*)(std::string)> calc_map; // syntax that compiles...

Question 1: Is this some idiosyncratic issue with clang (I am on an old Mac laptop because my linux machine is dead!) or did Stroustrup forget to add the (*) in his example? Am I missing something else?

Further, his example uses an alias, which in my simple calculation example translated at first to:

using Pf = int(std::string); // compiler actually seems to think this is fine
std::map<std::string,Pf> calc_map; // compiler does not like this

and when fixed became...

using Pf = int(*)(std::string); // compiler thinks this is fine too
std::map<std::string,Pf> calc_map; // compiler also likes this and everything works

Question 2: What kind of thing is an int(std::string) that the compiler doesn't mind it as an alias?

Possibly useful version stuff from clang:

Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.1.0

Thanks!

Aucun commentaire:

Enregistrer un commentaire