Here, the mighty lambda!
#include <iostream> template <typename T> void myFunction(T t) { t(); } int main() { myFunction([](){ std::cout << "Hi!" << std::endl; }); }
If you want to know more about them, look here.
To decrypt this a bit, here is a breakdown:
- You have a function that takes another function through a template argument.
- This function does nothing but call its argument.
- Inside main, you call this function with a lambda as an argument.
- The lambda can be divided into three parts
[] (capture, do not worry about it for too long) () arguments of the function, in this case they are not) and { ... } (the body, like any other function).
So the lambda part is simple:
[](){ std::cout << "Hi!" << std::endl; }
Here is another lambda example that takes an int and returns double its value:
[](int value){ return value * 2; }
source share