Local functions (a.k.a., nested
functions) are a form of information hiding
and they are useful for dividing procedural tasks into subtasks which are only
meaningful locally, avoiding cluttering other parts of the program with functions,
variables, etc unrelated to those parts. Therefore, local functions complement
other structuring possibilities such as namespaces and classes. Local functions
are a feature of many programming languages, notably Pascal
and Ada,
yet lacking from C++03
(see also [N2511]).

intmain(void){// Some local scope.intsum=0,factor=10;// Variables in scope to bind.autoadd=[factor,&sum](intnum){// C++11 only.sum+=factor*num;};add(1);// Call the lambda.intnums[]={2,3};std::for_each(nums,nums+2,add);// Pass it to an algorithm.BOOST_TEST(sum==60);// Assert final summation value.returnboost::report_errors();}

This library allows to program local functions portably between C++03
and C++11 (and
with performances comparable to lambda functions on C++11
compilers). For example (see also add.cpp):

intmain(void){// Some local scope.intsum=0,factor=10;// Variables in scope to bind.voidBOOST_LOCAL_FUNCTION(constbindfactor,bind&sum,intnum){sum+=factor*num;}BOOST_LOCAL_FUNCTION_NAME(add)add(1);// Call the local function.intnums[]={2,3};std::for_each(nums,nums+2,add);// Pass it to an algorithm.BOOST_TEST(sum==60);// Assert final summation value.returnboost::report_errors();}

This library supports the following features for local functions:

Local functions can capture, or better bind,
any of the variables from the enclosing scope (a function together with
its captured variables is also called a closure).

The local function body is programmed using the usual C++ statement syntax
(as a consequence, compiler errors and debugging retain their usual meaning
and format).

Local functions can be passed as template parameters so they can be conveniently
used with STL algorithms and other templates. [1]

However, local functions must be specified within a declarative context
(e.g., at a point in the code where local variables can be declared) thus
they cannot be specified within expressions. [2]