For all intents and purposes, C++ supports this via lambdas:1
int main() {
auto f = []() { return 42; };
std::cout << "f() = " << f() << std::endl;
}
Here, f
is a lambda object that acts as a local function in main
. Captures can be specified to allow the function to access local objects.
Behind the scenes, f
is a function object (i.e. an object of a type that provides an operator()
). The function object type is created by the compiler based on the lambda.
1 since C++11