I'm trying to make an application that stores pairs of the type <std:string, Function> into a std::map. Basically I want to do this:
mymap.find("printf")->second("Print this string.");
But I don't know how to define the second part of the pair. Is there a general type that points to a function? I read on a forum that you could do it, but they deleted the post, so that's why I'm asking here.
It's a bad idea to use the results of find like that.
1. find may return mymap.end(), in which case you can't do the dereference as there is no second.
2. if you need to use the result more than once, you're doing a binary search each time you want to get hold of the iterator again.
Having said that, here's some code showing the syntax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <map>
#include <string>
#include <iostream>
typedef std::map<std::string, std::string> strmap_t;
int main()
{
strmap_t m;
m["printf"] = "Print this string";
std::cout << m.find("printf")->second << std::endl;
return 0;
}
I know I'm getting annoying, but I should have mentioned this. I knew this method of typedefing the function. I wanted to know if there is a more general way, that applies to any function. Because, for example, in the example you gave me I could only store functions that receive one std::string& as a parameter.
Functions with different signatures are different types. I'm not sure what you want, but if it's a printf style function that you're after then then use one instead.
Of course, there's a host of reasons why printf shouldn't be used in C++, but that's another matter.
As long as it's not inherently unsafe and making it be safe is my job, I'm fine with it. Not trying to be a rebel, but the way I see, C I/O functions are faster(I know...some long philosophy about how that's relative, but for my purposes they are) and with C++ you get the added bonus of classes and abstractization in general.
Faster? I don't know. Consider that printf() takes a format string that has to be parsed whereas streams do not. And although it seems like streams incur a lot of function calls, consider that most of them are probably inlined.
I work on a project that has well over a million lines of code. We had a typedef of a type to a POD-type (eg, unsigned long). At one point, we needed to change the typedef to a real type that was implemented as a class. It was hard enough to do as it was, but what made things worse was the some 1,000+ places where the type was printed using printf( "%lu", var ), since now every single occurrence had to change. Why not just write an operator unsigned long(), you ask? Because being able to manipulate the type using built-in integer math defeated the purpose of making it a class in the first place.