![]() |
Home | Libraries | People | FAQ | More |
This section illustrates advanced usages of this library (at the bottom there is also a list of known limitations of the library).
This library also allows to specify default values for the local function
parameters. However, the usual C++ syntax for default parameters that uses
the assignment symbol = cannot
be used. [17] The keyword default
is used instead:
parameter-type parameter-name, defaultparameter-default-value, ...
For example, let's program a local function add(x,
y)
where the second parameter y
is optional and has a default value of 2
(see also add_default.cpp):
int BOOST_LOCAL_FUNCTION(int x, int y, default 2) { // Default. return x + y; } BOOST_LOCAL_FUNCTION_NAME(add) BOOST_CHECK( add(1) == 3 );
Programmers can define a WITH_DEFAULT
macro similar to the following if they think it improves readability over
the syntax above (see also add_with_default.cpp):
[18]
#define WITH_DEFAULT , default
int BOOST_LOCAL_FUNCTION(int x, int y WITH_DEFAULT 2) { // Default. return x + y; } BOOST_LOCAL_FUNCTION_NAME(add) BOOST_CHECK( add(1) == 3 );
The C++ preprocessor does not allow commas ,
within macro parameters unless they are wrapped by round parenthesis () (see the Boost.Utility/IdentityType
documentation for details). Therefore, using commas within the local function
parameters and bindings will generate (cryptic) preprocessor errors unless
they are wrapped with an extra set of round parenthesis ()
as explained here.
![]() |
Note |
|---|---|
Also macro parameters with commas wrapped by angular parenthesis |
In addition, local function parameter types cannot start with non-alphanumeric
symbols (alphanumeric symbols are A-Z, a-z,
and 0-9). [19] The library will generate (cryptic) preprocessor errors if a
parameter type starts with a non-alphanumeric symbol.
Let's consider the following example:
void BOOST_LOCAL_FUNCTION( const std::map<std::string, size_t>& m, // (1) Error. ::sign_t sign, // (2) Error. const size_t& factor, default key_sizeof<std::string, size_t>::value, // (3) Error. const std::string& separator, default cat(":", " ") // (4) OK. ) { ... } BOOST_LOCAL_FUNCTION_NAME(f)
(1) The parameter type const
std::map<std::string, size_t>& contains a comma ,
after the first template parameter std::string.
This comma is not wrapped by any round parenthesis ()
thus it will cause a preprocessor error. [20] The Boost.Utility/IdentityType
macro BOOST_IDENTITY_TYPE(parenthesized-type) from the header boost/utility/identity_type.hpp
can be used to wrap a type within extra parenthesis ()
so to overcome the problem:
#include <boost/utility/identity_type.hpp> void BOOST_LOCAL_FUNCTION( BOOST_IDENTITY_TYPE((const std::map<std::string, size_t>&)) m, // OK. ... ) { ... } BOOST_LOCAL_FUNCTION_NAME(f)
This macro expands to an expression that evaluates (at compile-time) exactly
to the specified type. Note that a total of two set of parenthesis () are needed: The parenthesis to invoke the
BOOST_IDENTITY_TYPE(...)
macro plus the parenthesis to wrap the type expression (and therefore any
comma , that it contains) passed
as parameter to the BOOST_IDENTITY_TYPE((...)) macro. Finally, the BOOST_IDENTITY_TYPE macro must be prefixed
by the typename keyword typename BOOST_IDENTITY_TYPE(parenthesized-type) when used together with the BOOST_LOCAL_FUNCTION_TPL
macro within templates.
![]() |
Note |
|---|---|
Often, there might be better ways to overcome this limitation that lead
to code which is more readable than the one using the |
For example, in this case a typedef
from the enclosing scope could have been used to obtain the following valid
and perhaps more readable code:
typedef std::map<std::string, size_t> map_type; void BOOST_LOCAL_FUNCTION( const map_type& m, // OK (and more readable). ... ) BOOST_LOCAL_FUNCTION_NAME(f)
(2) The parameter type ::sign_t starts with the non-alphanumeric
symbols :: thus it will generate
preprocessor errors if used as a local function parameter type. The macros
BOOST_IDENTITY_TYPE can also
be used to overcome this issue:
void BOOST_LOCAL_FUNCTION( ... BOOST_IDENTITY_TYPE((::sign_t)) sign, // OK. ... ) { ... } BOOST_LOCAL_FUNCTION_NAME(f)
![]() |
Note |
|---|---|
Often, there might be better ways to overcome this limitation that lead
to code which is more readable than the one using the |
For example, in this case the symbols ::
could have been simply dropped to obtain the following valid and perhaps
more readable code:
void BOOST_LOCAL_FUNCTION( ... sign_t sign, // OK (and more readable). ... ) { ... } BOOST_LOCAL_FUNCTION_NAME(f)
(3) The default parameter value key_sizeof<std::string, size_t>::value
contains a comma , after the
first template parameter std::string.
Again, this comma is not wrapped by any parenthesis ()
so it will cause a preprocessor error. Because this is a value expression
(and not a type expression), it can be simply wrapped within an extra set
of round parenthesis ():
void BOOST_LOCAL_FUNCTION( ... const size_t& factor, default (key_sizeof<std::string, size_t>::value), // OK. ... ) { ... } BOOST_LOCAL_FUNCTION_NAME(f)
(4) The default parameter value cat(":", " ") is instead fine because it contains a comma
, which is already wrapped by
the parenthesis () of the function
call cat(...).
Consider the following complete example (see also macro_commas.cpp):
void BOOST_LOCAL_FUNCTION( BOOST_IDENTITY_TYPE((const std::map<std::string, size_t>&)) m, BOOST_IDENTITY_TYPE((::sign_t)) sign, const size_t& factor, default (key_sizeof<std::string, size_t>::value), const std::string& separator, default cat(":", " ") ) { // Do something... } BOOST_LOCAL_FUNCTION_NAME(f)
Local functions are function objects so it is possible to assign them to
other functors like Boost.Function
boost::function in order to store the local function
into a variable, pass it as a parameter to another function, or return it
from the enclosing function.
For example (see also return_assign.cpp):
void call1(boost::function<int (int) > f) { BOOST_CHECK( f(1) == 5 ); } void call0(boost::function<int (void)> f) { BOOST_CHECK( f() == 5 ); } boost::function<int (int, int)> linear(const int& slope) { int BOOST_LOCAL_FUNCTION(const bind& slope, int x, default 1, int y, default 2) { return x + slope * y; } BOOST_LOCAL_FUNCTION_NAME(lin) boost::function<int (int, int)> f = lin; // Assign to local variable. BOOST_CHECK( f(1, 2) == 5 ); call1(lin); // Pass to other functions. call0(lin); return lin; // Return. } void call(void) { boost::function<int (int, int)> f = linear(2); BOOST_CHECK( f(1, 2) == 5 ); }
Note that:
![]() |
Warning |
|---|---|
As with C++11 lambda functions, programmers are responsible to ensure that bound variables are valid in any scope where the local function object is called. Returning and calling a local function outside its declaration scope will lead to undefined behaviour if any of the bound variable is no longer valid in the scope where the local function is called (see the __Example__ section for more examples on the extra care needed when returning a local function closure). It is always safe instead to call a local function within its declaration scope. |
In addition, a local function can bind and call another local function. Local
functions should always be bound by constant reference const
bind&
to avoid unnecessary copies. For example, the following local function inc_sum binds the local function inc so inc_sum
can call inc (see aslo transform.cpp):
int offset = 5; std::vector<int> v; std::vector<int> w; for(int i = 1; i <= 2; ++i) v.push_back(i * 10); BOOST_CHECK( v[0] == 10 ); BOOST_CHECK( v[1] == 20 ); w.resize(v.size()); int BOOST_LOCAL_FUNCTION(const bind& offset, int i) { return ++i + offset; } BOOST_LOCAL_FUNCTION_NAME(inc) std::transform(v.begin(), v.end(), w.begin(), inc); BOOST_CHECK( w[0] == 16 ); BOOST_CHECK( w[1] == 26 ); int BOOST_LOCAL_FUNCTION(bind& inc, int i, int j) { return inc(i + j); // Call the other bound local function. } BOOST_LOCAL_FUNCTION_NAME(inc_sum) offset = 0; std::transform(v.begin(), v.end(), w.begin(), v.begin(), inc_sum); BOOST_CHECK( v[0] == 27 ); BOOST_CHECK( v[1] == 47 );
It is possible to nest local functions into one another. For example (see
also nesting.cpp):
int x = 0; void BOOST_LOCAL_FUNCTION(bind& x) { void BOOST_LOCAL_FUNCTION(bind& x) { // Nested. x++; } BOOST_LOCAL_FUNCTION_NAME(g) x--; g(); // Nested local function call. } BOOST_LOCAL_FUNCTION_NAME(f) f();
This library never requires to explicitly specify the type of bound variables. From within local functions, programmers can access the type of a bound variable using the following macro:
BOOST_LOCAL_FUNCTION_TYPEOF(bound-variable-name)
The BOOST_LOCAL_FUNCTION_TYPEOF
macro expands to a type expression that evaluates (at compile-time) to the
fully qualified type of the bound variable with the specified name. This
type expression is fully qualified in the sense that it will be constant
if the variable is bound by constant const
bind[&]
and it will also be a reference if the variable is bound by reference [const]
bind&
(if needed, programmers can remove the const
and & qualifiers using
boost::remove_const and boost::remove_reference,
see Boost.TypeTraits).
The deduced bound type can be used within the body to check concepts, declare
local variables, etc. For example (see also typeof.cpp
and addable.hpp):
int sum = 0, factor = 10; void BOOST_LOCAL_FUNCTION(const bind factor, bind& sum, int num) { // Typeof for concept checking. BOOST_CONCEPT_ASSERT((Addable<boost::remove_reference< BOOST_LOCAL_FUNCTION_TYPEOF(sum)>::type>)); // Typeof for declarations. boost::remove_reference<BOOST_LOCAL_FUNCTION_TYPEOF( factor)>::type mult = factor * num; sum += mult; } BOOST_LOCAL_FUNCTION_NAME(add) add(6);
Within templates, BOOST_LOCAL_FUNCTION_TYPEOF
should not be prefixed by the typename
keyword but eventual type manipulations need the typename
prefix as usual (see also typeof_template.cpp
and addable.hpp):
template<typename T> T calculate(const T& factor) { T sum = 0; void BOOST_LOCAL_FUNCTION_TPL(const bind factor, bind& sum, T num) { // Local function `TYPEOF` does not need `typename`. BOOST_CONCEPT_ASSERT((Addable<typename boost::remove_reference< BOOST_LOCAL_FUNCTION_TYPEOF(sum)>::type>)); sum += factor * num; } BOOST_LOCAL_FUNCTION_NAME(add) add(6); return sum; }
It is best to use the BOOST_LOCAL_FUNCTION_TYPEOF
macro instead of using Boost.Typeof
so to reduce the number of times that Boost.Typeof
is invoked:
Furthermore, within the local function body it possible to access the result
type using result_type, the
type of the first parameter using arg1_type,
the type of the second parameter using arg2_type,
etc. [21]
Local functions can be declared inline to increase the chances that the compiler
will be able to reduce the run-time of the local function call by inlining
the generated assembly code. A local function is declared inline by prefixing
its name with the keyword inline:
result-type BOOST_LOCAL_FUNCTION(parameters) { ... // Body. } BOOST_LOCAL_FUNCTION_NAME(inline name) // Inlining.
When inlining a local function, note the following:
boost::function)
and they cannot be passed as template parameters.
inline has no
effect because this library will automatically generate code that uses
C++11 specific
features to inline the local function calls whenever possible even if
the local function is not declared inline. Furthermore, non C++11
local functions can always be passes as template parameters even when
they are declared inline. [23]
![]() |
Important |
|---|---|
It is recommended to not declare a local function inline unless it is strictly necessary for optimizing pure C++03 compliant code (because in all other cases this library will automatically take advantage of C++11 features to optimize the local function calls while always allowing to pass the local function as a template parameter). |
For example, the following local function is declared inline (thus a for-loop
needs to be used for portability instead of passing the local function as
a template parameter to the std::for_each
algorithm, see also add_inline.cpp):
int sum = 0, factor = 10; void BOOST_LOCAL_FUNCTION(const bind factor, bind& sum, int num) { sum += factor * num; } BOOST_LOCAL_FUNCTION_NAME(inline add) // Inlined. std::vector<int> v(100); std::fill(v.begin(), v.end(), 1); for(size_t i = 0; i < v.size(); ++i) add(v[i]); // Cannot use for_each.
Local functions can be declared recursive
so a local function can recursively call itself from its body (as usual with
C++ functions). A local function is declared recursive by prefixing its name
with the "keyword" recursive
(thus recursive cannot be
used as a local function name):
result-type BOOST_LOCAL_FUNCTION(parameters) { ... // Body. } BOOST_LOCAL_FUNCTION_NAME(recursive name) // Recursive.
For example, the following local function is used to recursively calculate
the factorials of all the numbers in the specified vector (see also factorial.cpp):
struct calculator { std::vector<int> results; void factorials(const std::vector<int>& nums) { int BOOST_LOCAL_FUNCTION(bind this_, int num, bool recursion, default false) { int result = 0; if(num <= 0) result = 1; else result = num * factorial(num - 1, true); // Recursive call. if(!recursion) this_->results.push_back(result); return result; } BOOST_LOCAL_FUNCTION_NAME(recursive factorial) // Recursive. std::for_each(nums.begin(), nums.end(), factorial); } };
Compilers have not been observed to be able to inline recursive local function
calls (not even when the recursive local function is also declared inline
as in BOOST_LOCAL_FUNCTION_NAME(inline recursive
factorial)).
![]() |
Warning |
|---|---|
Recursive local functions should never be called outside their declaration scope. If a local function is returned from the enclosing function and called in a different scope, the behaviour is undefined (and it will likely result in a run-time error). [24] This is not a limitation with respect to C++11 lambda functions because lambdas can never call themselves recursively (in other words, there is no recursive lambda function that can successfully be called outside its declaration scope because there is no recursive lambda function at all). |
It is possible to overload local functions using the boost::overloaded_function
functor of Boost.Functional/OverloadedFunction
from the header boost/functional/overloaded_function.hpp
(see the Boost.Functional/OverloadedFunction
documentation for details).
In the following example, the overloaded function object add
can be called with signatures from either the local function add_s, or the local function add_d, or the local function add_d with its extra default parameter,
or the function pointer add_i
(see also overload.cpp):
int add_i(int x, int y) { return x + y; } BOOST_AUTO_TEST_CASE( test_overload ) { std::string s = "abc"; std::string BOOST_LOCAL_FUNCTION( const bind& s, const std::string& x) { return s + x; } BOOST_LOCAL_FUNCTION_NAME(add_s) double d = 1.23; double BOOST_LOCAL_FUNCTION(const bind d, double x, double y, default 0) { return d + x + y; } BOOST_LOCAL_FUNCTION_NAME(add_d) boost::overloaded_function< std::string (const std::string&) , double (double) , double (double, double) // Overload giving default param. , int (int, int) > add(add_s, add_d, add_d, add_i); // Overloaded function object. BOOST_CHECK( add("xyz") == "abcxyz" ); // Call `add_s`. BOOST_CHECK( fabs(add(3.21) - 4.44) < 0.001 ); // Call `add_d` (no default). BOOST_CHECK( fabs(add(3.21, 40.0) - 44.44) < 0.001); // Call `add_d`. BOOST_CHECK( add(1, 2) == 3 ); // Call `add_i`. }
It is possible to program exception specifications for local functions by
specifying them after the BOOST_LOCAL_FUNCTION
macro and before the body code block {
... }.
![]() |
Important |
|---|---|
Note that the exception specifications only apply to the body code specified
by programmers and they do not apply to the rest of the code automatically
generated by the macro expansions to implement local functions. For example,
even if the body code is specified to throw no exception using |
For example (see also add_except.cpp):
double sum = 0.0; int factor = 10; void BOOST_LOCAL_FUNCTION(const bind factor, bind& sum, double num) throw() { // Throw nothing. sum += factor * num; } BOOST_LOCAL_FUNCTION_NAME(add) add(100);
Local function parameters support the storage classifiers as usual in C++03.
The auto storage classifier
is specified as: [25]
auto parameter-type parameter-name
The register storage classifier
is specified as:
register parameter-type parameter-name
For example (see also add_classifiers.cpp):
int BOOST_LOCAL_FUNCTION(auto int x, register int y) { // Classifiers. return x + y; } BOOST_LOCAL_FUNCTION_NAME(add)
The following table summarizes all C++ function features indicating those features that are not supported by this library for local functions.
|
C++ Function Feature |
Local Function Support |
Comment |
|---|---|---|
|
|
No |
This is not supported because local functions cannot be templates
(plus most C++ compilers do not implement |
|
|
No |
This is not supported because local functions are implemented using local classes and C++03 local classes cannot be templates. |
|
|
No |
This is not supported because local functions are not constructors. |
|
|
Yes |
Local functions can be specified |
|
|
No |
This is not supported because local functions are always defined locally within the enclosing scope and together with their declarations. |
|
|
No |
This is not supported because local functions are not member functions. |
|
|
No |
This is not supported because local functions are not member functions. [a] |
|
|
Yes |
This is supported (see the Tutorial section). |
|
|
Yes |
Local functions are named and they can call themselves recursively but they cannot be operators (see the Tutorial and Advanced Topics sections). |
|
|
Yes |
This is supported and it also supports the |
|
Trailing |
No |
This is not supported because local functions are not member functions. |
|
Trailing |
No |
This is not supported because local functions are not member functions. |
[a] Rationale. It would be possible to make a local function class inherit from another local function class. However, this "inheritance" feature is not implemented because it seemed of no use given that local functions can be bound to one another thus they can simply call each other directly without recurring to dynamic binding or base function call. | ||
Local functions cannot be operators. Naming a local function operator...
will generate a compile-time error. [26]
For example, the following code will not compile (see also operator_error.cpp):
struct point { int x; int y; }; BOOST_AUTO_TEST_CASE( test_operator_err ) { bool BOOST_LOCAL_FUNCTION(const point& p, const point& q) { return p.x == q.x && p.y == q.y; } BOOST_LOCAL_FUNCTION_NAME(operator==) // Error: Cannot use `operator...`. point a; a.x = 1; a.y = 2; point b = a; BOOST_CHECK( a == b ); }
It is not possible to jump with a goto
from within a local function to a label defined in the enclosing scope.
For example, the following will not compile (see also goto_error.cpp):
int error(int x, int y) { int BOOST_LOCAL_FUNCTION(int x) { if(x <= 0) goto failure; // Error: Cannot jump to enclosing scope. else goto success; // OK: Can jump within local function. success: return 0; } BOOST_LOCAL_FUNCTION_NAME(validate) return validate(x + y); faliure: return -1; }
[17]
Rationale. The assignment symbol = cannot be used to specify default parameter
values because default values are not part of the parameter type so they
cannot be handled using template meta-programming. Default parameter values
need to be separated from the rest of the parameter declaration using the
preprocessor. Specifically, this library needs to use preprocessor meta-programming
to remove default values when constructing the local function type and
then to count the number of default values to provide the correct set of
call operators for the local functor. Therefore, the symbol = cannot be used because it cannot be handled
by preprocessor meta-programming (non-alphanumeric symbols cannot be detected
by preprocessor meta-programming because they cannot be concatenated by
the preprocessor).
[18]
The authors do not personally find the use of the WITH_DEFAULT
macro more readable and they prefer to use the default
keyword directly. Furthermore, WITH_DEFAULT
needs to be defined differently for compilers without variadic macros
#define WITH_DEFAULT
(default) so it can only be defined by programmers
based on the syntax they decide to use.
[19]
Rationale. This limitation is because
this library uses preprocessor token concatenation ##
to inspect the macro parameters (to distinguish between function parameters,
bound variables, etc) and the C++ preprocessor does not allow to concatenate
non-alphanumeric tokens.
[20]
The preprocessor always interprets unwrapped commas as separating macro
parameters. Thus in this case the comma will indicate to the preprocessor
that the first macro parameter is const
std::map<std::tring, the second macro parameter is
size_t>&
m, etc instead of passing const std::map<std::string, size_t>& m
as a single macro parameter.
[21]
Rationale. The type names result_type and argN_type follow the Boost.TypeTraits
naming conventions for function traits.
[22] In the examples of this documentation, we specify bound variables, function parameters, and result type in this order because this is the order used by C++11 lambda functions. However, the library accepts bound variables, function parameters, and the result type in any order.
[23] Rationale. This library uses an indirect function call via a function pointer in order to pass the local function as a template parameter (see the Implementation section). No compiler has yet been observed to be able to inline function calls when they use such indirect function pointer calls. Therefore, inlined local functions do not use such indirect function pointer call (so they are more likely to be optimized) but because of that they cannot be passed as template parameters. The indirect function pointer call is needed on C++03 but it is not needed on C++11 (see [N2657]) thus this library automatically generates local function calls that can be inlined on C++11 compilers (even when the local function is not declared inline).
[24]
Rationale. This limitation comes from
the fact that the global functor used to pass the local function as a
template parameter (and eventually returned outside the declarations
scope) does not know the local function name so the local function name
used for recursive call cannot be set in the global functor. This limitation
together with preventing the possibility for inlining are the reasons
why local functions are not recursive unless programmers explicitly declare
them recursive.
[25]
The auto storage classifier
is part of the C++03
standard and therefore supported by this library. However, the meaning
and usage of the auto keyword
changed in C++11.
Therefore, use the auto storage
classifier with the usual care in order to avoid writing C++03
code that might not work on C++11.
[26] Rationale. This is the because a local function name must be a valid local variable name (the local variable used to hold the local functor) and operators cannot be used as local variable names.