The accepted answer is very useful and quite comprehensive. However, the OP states
I would like to see a simple example to write a callback function.
So here you go, from C++11 you have std::function
so there is no need for function pointers and similar stuff:
#include <functional>
#include <string>
#include <iostream>
void print_hashes(std::function<int (const std::string&)> hash_calculator) {
std::string strings_to_hash[] = {"you", "saved", "my", "day"};
for(auto s : strings_to_hash)
std::cout << s << ":" << hash_calculator(s) << std::endl;
}
int main() {
print_hashes( [](const std::string& str) { /** lambda expression */
int result = 0;
for (int i = 0; i < str.length(); i++)
result += pow(31, i) * str.at(i);
return result;
});
return 0;
}
This example is by the way somehow real, because you wish to call function print_hashes
with different implementations of hash functions, for this purpose I provided a simple one. It receives a string, returns an int (a hash value of the provided string), and all that you need to remember from the syntax part is std::function<int (const std::string&)>
which describes such function as an input argument of the function that will invoke it.