In C#, what I want would look something like this:
IDictionary<string, action()> dict = new Dictionary<string, action()>();
How do I do this in C++? This gives compiler errors:
map<string, void()> exercises;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use boost::function, a polymorphous wrapper for any object that can be called with your signature (including functions, function objects etc).
Note that the new C++ standard has already included
functionin<functional>.To explain the backgrounds: The only builtin mechanism of this kind in C++ are old C-style function pointers (
void (*)()). These are extremely low-level, basically just storing the memory address of a function, and therefore far from even coming close to the power of C#’s delegates.You can’t create anonymous functions, neither can you refer to a particular object’s member functions or any variables or data (closures).
Thus, one often utilizes so called functors which are classes that mimic the behaviour of a function by overloading the
operator (). In combination with templates, they are used whereever ordinary function pointers can be used.The problem is that these functors often consist of peculiar or anonymous types that can’t be referred to conveniently.
The
functionis the coolest way to address them all – Everything that behaves like a function, including cool new lambda-style expressions.