### Boost Local Function: Return and Assign (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/return_assign Demonstrates defining a local function using BOOST_LOCAL_FUNCTION, assigning it to a boost::function object, passing it to other functions, and returning it. This example highlights the flexibility of local functions within C++ and their integration with the Boost.Function library. ```C++ // Copyright (C) 2009-2012 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/local_function #include #ifdef BOOST_NO_CXX11_VARIADIC_MACROS # error "variadic macros required" #else #include #include #include #include //[return_assign void call1(boost::function f) { BOOST_TEST(f(1) == 5); } void call0(boost::function f) { BOOST_TEST(f() == 5); } boost::function 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 f = lin; // Assign to local variable. BOOST_TEST(f(1, 2) == 5); call1(lin); // Pass to other functions. call0(lin); return lin; // Return. } void call(void) { boost::function f = linear(2); BOOST_TEST(f(1, 2) == 5); } //] int main(void) { call(); return boost::report_errors(); } #endif // VARIADIC_MACROS ``` -------------------------------- ### Boost Local Function: Basic and Capture Examples Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/all_decl_seq Illustrates the basic syntax of BOOST_LOCAL_FUNCTION for defining local functions. It shows how to define functions with default arguments and how to capture external variables using `bind`. ```C++ namespace { struct s { void f() { void BOOST_LOCAL_FUNCTION( (int x) (int y)(default 0) ) { } BOOST_LOCAL_FUNCTION_NAME(ct) ct(1); void BOOST_LOCAL_FUNCTION( (const bind a) (const bind& b) (const bind& p) (bind this_) (int x) (int y)(default 0) ) { } BOOST_LOCAL_FUNCTION_NAME(pt) pt(1); void BOOST_LOCAL_FUNCTION( (const bind a) (const bind this_) (const bind& b) (const bind& p) (bind c) (bind& d) (bind& q) (int x) (int y)(default 0) ) { } BOOST_LOCAL_FUNCTION_NAME(lct) lct(1); void BOOST_LOCAL_FUNCTION( (const bind a) (const bind& b) (const bind& p) (bind c) (bind& d) (bind this_) (bind& q) (int x) (int y)(default 0) ) { } BOOST_LOCAL_FUNCTION_NAME(lpt) lpt(1); } }; } // namespace int main(void) { s().f(); return 0; } ``` -------------------------------- ### Complete Boost.LocalFunction and Derivative Computation Example Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/return_derivative Full working example showing local function definition, conversion to boost::function closures, and usage in higher-order functions. Includes variadic macro requirement check, type registration with BOOST_TYPEOF, and test validation demonstrating numerical derivative computation accuracy. ```cpp #include #ifdef BOOST_NO_CXX11_VARIADIC_MACROS # error "variadic macros required" #else #include #include #include #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() #include BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function, 1) boost::function derivative(boost::function& f, int dx) { int BOOST_LOCAL_FUNCTION(bind& f, const bind dx, int x) { return (f(x + dx) - f(x)) / dx; } BOOST_LOCAL_FUNCTION_NAME(deriv) return deriv; } int main(void) { int BOOST_LOCAL_FUNCTION(int x) { return x + 4; } BOOST_LOCAL_FUNCTION_NAME(add2) boost::function a2 = add2; boost::function d2 = derivative(a2, 2); BOOST_TEST(d2(6) == 1); return boost::report_errors(); } #endif ``` -------------------------------- ### BOOST_LOCAL_FUNCTION Macro Usage Example Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/doxygen/reference/local__function_8hpp_1a908ef82352c37bf49bcefc3ad41125a5 Demonstrates the typical usage pattern of the BOOST_LOCAL_FUNCTION macro within a declarative context. It includes the result type, macro, body, and the BOOST_LOCAL_FUNCTION_NAME macro for naming the local function. ```c++ { ... result_type BOOST_LOCAL_FUNCTION(declarations) { ... // Body code. } BOOST_LOCAL_FUNCTION_NAME(qualified_name) ... } ``` -------------------------------- ### Example: Local Function within a Template for Summation with Boost.LocalFunction Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/tutorial Provides a practical example of defining and using a local function within a C++ template. The local function 'add' is used to sum values, demonstrating binding of variables ('factor', 'sum') and use with `std::for_each`. It highlights the necessity of `_TPL` macros within templates. ```C++ template T total(const T& x, const T& y, const T& z) { T sum = T(), factor = 10; T BOOST_LOCAL_FUNCTION_TPL(const bind factor, bind& sum, T num) { return sum += factor * num; } BOOST_LOCAL_FUNCTION_NAME_TPL(add) add(x); T nums[2]; nums[0] = y; nums[1] = z; std::for_each(nums, nums + 2, add); return sum; } ``` -------------------------------- ### Local Function with Parameters Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/tutorial This example shows how to define a local function named 'add' that accepts two integer parameters, 'x' and 'y', and returns their sum. The parameters are passed to the BOOST_LOCAL_FUNCTION macro as a comma-separated list. The function is then called and its result asserted. ```cpp int BOOST_LOCAL_FUNCTION(int x, int y) { return x + y; } BOOST_LOCAL_FUNCTION_NAME(add) BOOST_TEST(add(1, 2) == 3); ``` -------------------------------- ### Overload Local Functions with Boost.Local_Function Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/overload Defines local functions using BOOST_LOCAL_FUNCTION and creates an overloaded function object using boost::overloaded_function. This example shows how to capture variables, use default parameters, and call the overloaded function with different argument types. It requires the Boost.Local_Function and Boost.Functional.Overloaded_Function headers. ```C++ // Copyright (C) 2009-2012 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/local_function #include #ifdef BOOST_NO_CXX11_VARIADIC_MACROS # error "variadic macros required" #else #include #include // For overloading. #include #include #include //[overload_decl int add_i(int x, int y) { return x + y; } //] int main(void) { //[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_TEST(add("xyz") == "abcxyz"); // Call `add_s`. BOOST_TEST((4.44 - add(3.21)) <= 0.001); // Call `add_d` (no default). BOOST_TEST((44.44 - add(3.21, 40.0)) <= 0.001); // Call `add_d`. BOOST_TEST(add(1, 2) == 3); // Call `add_i`. //] return boost::report_errors(); } #endif // VARIADIC_MACROS ``` -------------------------------- ### Create Local Function with Default Argument using Boost.Local Function Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/add_with_default This C++ snippet defines a local function named `add` using Boost.Local Function. The function takes an integer `x` and an integer `y` with a default value of 2, specified using the `WITH_DEFAULT` macro. The function returns the sum of `x` and `y`. The example then tests this function. ```c++ //[add_with_default int BOOST_LOCAL_FUNCTION(int x, int y WITH_DEFAULT 2) { // Default. return x + y; } BOOST_LOCAL_FUNCTION_NAME(add) BOOST_TEST(add(1) == 3); //] ``` -------------------------------- ### Scope Exit Usage with Constant and Reference Binding Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Example demonstrating scope exit with const bind and reference binding to execute cleanup code when exiting enclosing scope. Supports constant binding for variables that should not be modified within the scope exit body. ```cpp person& p = persons_.back(); person::evolution_t checkpoint = p.evolution_; SCOPE_EXIT(const bind checkpoint, const bind& p, bind this_) { if (checkpoint == p.evolution_) this_->persons_.pop_back(); } SCOPE_EXIT_END ``` -------------------------------- ### Boost.Phoenix Function Creation from Local Function Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Creates a Boost.Phoenix lazy function from a local recursive factorial function. Demonstrates both eager and lazy evaluation using phoenix::function wrapper with local function implementations. ```cpp int main(void) { using boost::phoenix::arg_names::arg1; int BOOST_LOCAL_FUNCTION(int n) { return (n <= 0) ? 1 : n * factorial_impl(n - 1); } BOOST_LOCAL_FUNCTION_NAME(recursive factorial_impl) boost::phoenix::function< boost::function > factorial(factorial_impl); int i = 4; BOOST_TEST(factorial(i)() == 24); BOOST_TEST(factorial(arg1)(i) == 24); return boost::report_errors(); } ``` -------------------------------- ### Example: Explicitly Typed Local Function in C++ Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/advanced_topics An example demonstrating the explicit specification of bound variable types (factor, this_) and the return type (int) for a local function within a C++ struct. This example showcases the `bind` syntax and `BOOST_LOCAL_FUNCTION` usage. ```cpp struct adder { adder(void) : sum_(0) {} int sum(const std::vector& nums, const int& factor = 10) { // Explicitly specify bound variable and return types (no type-of). BOOST_LOCAL_FUNCTION(const bind(const int&) factor, bind(adder*) this_, int num, return int) { return this_->sum_ += factor * num; } BOOST_LOCAL_FUNCTION_NAME(add) std::for_each(nums.begin(), nums.end(), add); return sum_; } private: int sum_; }; ``` -------------------------------- ### Constant Block with C++ Syntax (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Shows an alternative syntax for creating constant blocks using C++ braces, achieving the same compile-time error detection as the N1613 macros when an assignment is mistaken for a comparison. ```cpp int x = 1, y = 2; const { // Constant block. assert(x = y); // Compiler error. } ``` -------------------------------- ### Using Default Parameter in Boost.Local_Function (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/add_default Defines a local function 'add' with a default value for the second parameter. This allows calling 'add(1)' which results in '1 + 2 = 3'. The example requires variadic macros, typically available in C++11 and later. ```cpp #include #include int main(void) { //[add_default int BOOST_LOCAL_FUNCTION(int x, int y, default 2) { // Default parameter. return x + y; } BOOST_LOCAL_FUNCTION_NAME(add) BOOST_TEST(add(1) == 3); //] return boost::report_errors(); } #endif // VARIADIC_MACROS ``` -------------------------------- ### Local Function with No Parameters Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/tutorial This snippet illustrates defining a local function that takes no parameters. 'void' is passed to the BOOST_LOCAL_FUNCTION macro, similar to standard C++ function declarations. The example defines a function 'ten' that always returns 10 and verifies its output. ```cpp int BOOST_LOCAL_FUNCTION(void) { return 10; } BOOST_LOCAL_FUNCTION_NAME(ten) BOOST_TEST(ten() == 10); ``` -------------------------------- ### C++ Example of Nested Local Functions with Boost.Local_Function Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/nesting This C++ code snippet showcases the nesting capability of Boost.Local_Function. It defines an outer local function 'f' which, in turn, defines and calls an inner local function 'g'. Both functions modify a bound variable 'x'. The example requires C++11 variadic macros. ```C++ #include #ifdef BOOST_NO_CXX11_VARIADIC_MACROS # error "variadic macros required" #else #include #include int main(void) { //[nesting 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(); //] BOOST_TEST(x == 0); return boost::report_errors(); } #endif // VARIADIC_MACROS ``` -------------------------------- ### GCC Lambda Function Macro Implementation with Local Functions Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Shows the internal implementation of GCC lambda function macros using Boost.LocalFunction and GCC statement expressions. These macros abstract the creation of callable objects that work similarly to C++11 lambdas. ```c++ # define GCC_LAMBDA_(binds, params, results) \ ({ /* open statement expression (GCC extension only) */ \ BOOST_LOCAL_FUNCTION( \ BOOST_PP_LIST_ENUM(BOOST_PP_LIST_APPEND(binds, \ BOOST_PP_LIST_APPEND(params, \ BOOST_PP_IIF(BOOST_PP_LIST_IS_NIL(results), \ (return void, BOOST_PP_NIL) /* default for lambdas */ \ , \ results \ ) ) )) ) ``` ```c++ #define GCC_LAMBDA_END_(id) \ BOOST_LOCAL_FUNCTION_NAME(BOOST_PP_CAT(gcc_lambda_, id)) \ BOOST_PP_CAT(gcc_lambda_, id); \ }) /* close statement expression (GCC extension only) */ ``` -------------------------------- ### GCC Lambdas with Local Functions vs. C++11 Lambdas Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Demonstrates the equivalent usage of GCC lambdas implemented with local functions and native C++11 lambdas for finding an element in an array. This showcases how Boost.LocalFunction emulates C++11 lambda behavior on older GCC compilers. ```c++ int val = 2; int nums[] = {1, 2, 3}; int* end = nums + 3; int* iter = std::find_if(nums, end, GCC_LAMBDA(const bind val, int num, return bool) { return num == val; } GCC_LAMBDA_END ); ``` ```c++ int val = 2; int nums[] = {1, 2, 3}; int* end = nums + 3; int* iter = std::find_if(nums, end, [val](int num) -> bool { return num == val; } ); ``` -------------------------------- ### Boost.Phoenix Function from Global Functor with Polymorphism Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Implements a polymorphic factorial functor for Boost.Phoenix with result type computation. Provides comparison to local function approach showing how polymorphic Phoenix functions require global functors. ```cpp struct factorial_impl { template struct result; template struct result : result {}; template struct result { typedef Arg type; }; template Arg operator()(Arg n) const { return (n <= 0) ? 1 : n * (*this)(n - 1); } }; int main(void) { using boost::phoenix::arg_names::arg1; boost::phoenix::function factorial; int i = 4; BOOST_TEST(factorial(i)() == 24); BOOST_TEST(factorial(arg1)(i) == 24); return boost::report_errors(); } ``` -------------------------------- ### Defining and Using a Named Local Function with Bindings Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/alternatives This example shows how to define a named local function using `BOOST_LOCAL_FUNCTION`. It demonstrates binding variables by value (`factor`) and reference (`sum`), and passing an integer argument (`num`). The named local function `add` is then called directly and also passed to `std::for_each` to perform summation. ```cpp int main(void) { int sum = 0, factor = 10; void BOOST_LOCAL_FUNCTION(const bind factor, bind& sum, int num) { sum += factor * num; } BOOST_LOCAL_FUNCTION_NAME(add) add(1); // Call the local function. int nums[] = {2, 3}; std::for_each(nums, nums + 2, add); // Pass it to an algorithm. BOOST_TEST(sum == 60); // Assert final summation value. return boost::report_errors(); } ``` -------------------------------- ### Define and Use Local Function with Captured Variables (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/add_seq Defines a local function 'add' using BOOST_LOCAL_FUNCTION that captures 'factor' by value and 'sum' by reference. It then uses this local function to accumulate results. Dependencies include Boost.Local Function and Boost.Test. ```cpp // Copyright (C) 2009-2012 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/local_function #include #include #include //[add_seq int main(void) { int sum = 0, factor = 10; void BOOST_LOCAL_FUNCTION( (const bind factor) (bind& sum) (int num) ) { sum += factor * num; } BOOST_LOCAL_FUNCTION_NAME(add) add(1); int nums[] = {2, 3}; std::for_each(nums, nums + 2, add); BOOST_TEST(sum == 60); return boost::report_errors(); } //] ``` -------------------------------- ### Boost.LocalFunction Example for Portable Local Functions Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/index Illustrates the usage of Boost.LocalFunction for creating portable local functions compatible with C++03 and C++11. This method uses the BOOST_LOCAL_FUNCTION and BOOST_LOCAL_FUNCTION_NAME macros to define and name the local function, allowing it to bind variables from the surrounding scope and be used with algorithms. ```cpp int main(void) { int sum = 0, factor = 10; void BOOST_LOCAL_FUNCTION(const bind factor, bind& sum, int num) { sum += factor * num; } BOOST_LOCAL_FUNCTION_NAME(add) add(1); int nums[] = {2, 3}; std::for_each(nums, nums + 2, add); BOOST_TEST(sum == 60); return boost::report_errors(); } ``` -------------------------------- ### Define and Call Local Function with Parameters (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/add_params_only Demonstrates how to define a local function named 'add' within the main function using BOOST_LOCAL_FUNCTION and BOOST_LOCAL_FUNCTION_NAME. This function takes two integer parameters and returns their sum. The example also shows how to call this local function and verify its output using BOOST_TEST. ```C++ #include #include int main(void) { //[add_params_only int BOOST_LOCAL_FUNCTION(int x, int y) { // Local function. return x + y; } BOOST_LOCAL_FUNCTION_NAME(add) BOOST_TEST(add(1, 2) == 3); // Local function call. //] return boost::report_errors(); } #endif // VARIADIC_MACROS ``` -------------------------------- ### Example Usage of Template Local Functions (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/same_line Demonstrates the usage of the `LOCAL_INC_DEC_TPL` macro within a template function `f`. It defines local increment and decrement functions for a given `delta` and tests their combined effect. ```c++ template void f(T& delta) { LOCAL_INC_DEC_TPL(delta) // Multiple local functions on same line. BOOST_TEST(dec(inc(123)) == 123); } ``` -------------------------------- ### Local Function Macro for Constant Blocks (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Defines the preprocessor macros used to implement constant blocks with Boost.LocalFunction. These macros utilize local functions to bind variables by constant reference, ensuring they remain unmodified within the block. ```cpp #define CONST_BLOCK_(variables) \ void BOOST_LOCAL_FUNCTION( \ BOOST_PP_IIF(BOOST_PP_LIST_IS_NIL(variables), \ void BOOST_PP_TUPLE_EAT(3) \ , \ BOOST_PP_LIST_FOR_EACH_I \ )(CONST_BLOCK_BIND_, ~, variables) \ ) ``` ```cpp #define CONST_BLOCK_END_(id) \ BOOST_LOCAL_FUNCTION_NAME(BOOST_PP_CAT(const_block_, id)) \ BOOST_PP_CAT(const_block_, id)(); /* call local function immediately */ ``` -------------------------------- ### Define and Use Local Function with Default Parameter - C++ Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/add_default_seq Demonstrates how to define a local function 'add' within 'main' using BOOST_LOCAL_FUNCTION. It shows how to specify parameters, including a default value for 'y', and how to invoke the local function. The example relies on the Boost.Local Function and Boost.LightweightTest libraries. ```cpp #include #include int main(void) { int BOOST_LOCAL_FUNCTION( (int x) (int y)(default 2) ) { return x + y; } BOOST_LOCAL_FUNCTION_NAME(add) BOOST_TEST(add(1) == 3); return boost::report_errors(); } ``` -------------------------------- ### C++11 Lambda Function Example for Local Functions Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/index Demonstrates how to implement local functions using C++11 lambda functions. This approach requires a C++11 compliant compiler and utilizes lambda capture lists to bind variables from the enclosing scope. The lambda can then be called directly or passed to algorithms like std::for_each. ```cpp int main(void) { int sum = 0, factor = 10; auto add = [factor, &sum](int num) { sum += factor * num; }; add(1); int nums[] = {2, 3}; std::for_each(nums, nums + 2, add); BOOST_TEST(sum == 60); return boost::report_errors(); } ``` -------------------------------- ### Use Local Function with STL Algorithm std::find_if Source: https://www.boost.org/doc/libs/latest/libs/local_function/example/n2550_find_if Demonstrates passing a Boost.LocalFunction as a template parameter to std::find_if algorithm to search for the first employee whose salary matches the filtering criteria defined in the 'between' local function. ```cpp std::vector::iterator i = std::find_if( employees.begin(), employees.end(), between); BOOST_TEST(i != employees.end()); BOOST_TEST(i->salary >= min_salary && i->salary < u_limit); ``` -------------------------------- ### Local Function with Internal Goto - C++ Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/advanced_topics Demonstrates the use of a `goto` statement within a local function to jump to a label defined inside the same local function. This is a valid operation, allowing control flow manipulation within the local scope. The example uses the `BOOST_LOCAL_FUNCTION` and `BOOST_LOCAL_FUNCTION_NAME` macros. ```cpp int error(int x, int y) { int BOOST_LOCAL_FUNCTION(int z) { if(z > 0) goto success; // OK: Can jump within local function. return -1; success: return 0; } BOOST_LOCAL_FUNCTION_NAME(validate) return validate(x + y); } ``` -------------------------------- ### Constant Binding with C++11 Lambdas and Extra Variables (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Demonstrates a workaround for C++11 lambda limitations in constant binding. It uses extra constant reference variables (`const_x`, `const_y`) to achieve const-correctness, but requires managing new names and can be less direct than local functions. ```cpp int x = 1, y = 2; const decltype(x)& const_x = x; // Constant so cannot be modified const decltype(y)& const_y = y; // and reference so no copy. [&const_x, &const_y]() { // Lambda functions (C++11 only). assert(const_x = const_y); // Unfortunately, `const_` names. }(); ``` -------------------------------- ### Define and Use Local Function with No Parameters (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/ten_void Demonstrates how to define a local function named 'ten' that takes no parameters and returns an integer value of 10. This is achieved using the BOOST_LOCAL_FUNCTION and BOOST_LOCAL_FUNCTION_NAME macros. The example then asserts that calling this local function returns the expected value. ```c++ #include #include int main(void) { //[ten_void int BOOST_LOCAL_FUNCTION(void) { // No parameter. return 10; } BOOST_LOCAL_FUNCTION_NAME(ten) BOOST_TEST(ten() == 10); //] return boost::report_errors(); } ``` -------------------------------- ### Constant Block with N1613 Macros (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Illustrates using N1613-style CONST_BLOCK macros to enforce constant-binding for variables within the block. This setup causes a compile-time error when an assignment operator is mistakenly used instead of the comparison operator. ```cpp int x = 1, y = 2; CONST_BLOCK(x, y) { // Constant block. assert(x = y); // Compiler error. } CONST_BLOCK_END ``` -------------------------------- ### BOOST_LOCAL_FUNCTION Macro Synopsis Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/doxygen/reference/local__function_8hpp_1a908ef82352c37bf49bcefc3ad41125a5 This snippet shows the basic syntax for the BOOST_LOCAL_FUNCTION macro, which is used to initiate the declaration of a local function. It requires the `` header. ```c++ // In header: BOOST_LOCAL_FUNCTION(declarations) ``` -------------------------------- ### Define a Local Function using Boost Macros Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/tutorial This code demonstrates the basic syntax for defining a local function using Boost.LocalFunction macros. It requires including the 'boost/local_function.hpp' header and must be used within a declarative context. The macros define a function object with a specified name, result type, parameters, and body. ```cpp #include ... { ... _result-type_ BOOST_LOCAL_FUNCTION(_parameters_) { _body-code_ } BOOST_LOCAL_FUNCTION_NAME(_name_) ... } ``` -------------------------------- ### Define and Use Local Function with Bindings in C++ Source: https://www.boost.org/doc/libs/latest/libs/local_function/example/profile_local_function_inline Demonstrates how to define a local function 'add' using BOOST_LOCAL_FUNCTION and capture variables 'sum' and 'factor' by reference using 'bind'. The function modifies 'sum' based on the input 'num' and captured 'factor'. Includes timing for declaration and execution. ```c++ // Copyright (C) 2009-2012 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/local_function #include #include #include #include #include #include "profile_helpers.hpp" int main(int argc, char* argv[]) { unsigned long size = 0, trials = 0; profile::args(argc, argv, size, trials); double sum = 0.0; int factor = 1; boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); void BOOST_LOCAL_FUNCTION( const double& num, bind& sum, const bind& factor) { sum += factor * num; } BOOST_LOCAL_FUNCTION_NAME(inline add) // Inlined. boost::chrono::duration decl_sec = boost::chrono::system_clock::now() - start; std::vector v(size); std::fill(v.begin(), v.end(), 1.0); boost::chrono::duration trials_sec; for(unsigned long i = 0; i < trials; ++i) { boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); for(unsigned long j = 0; j < v.size(); ++j) add(v[j]); // No for_each. trials_sec += boost::chrono::system_clock::now() - start; } profile::display(size, trials, sum, trials_sec.count(), decl_sec.count()); return 0; } ``` -------------------------------- ### C++ Local Function Definition and Usage Source: https://www.boost.org/doc/libs/latest/libs/local_function/example/profile_local_function This C++ code snippet demonstrates the definition and usage of a local function using the Boost.Local_Function library. It shows how to capture variables by reference and use the local function within standard library algorithms like std::for_each. Includes performance profiling setup and display. ```C++ #include #include #include #include #include #include "profile_helpers.hpp" int main(int argc, char* argv[]) { unsigned long size = 0, trials = 0; profile::args(argc, argv, size, trials); double sum = 0.0; int factor = 1; boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); void BOOST_LOCAL_FUNCTION( const double& num, bind& sum, const bind& factor) { sum += factor * num; } BOOST_LOCAL_FUNCTION_NAME(add) boost::chrono::duration decl_sec = boost::chrono::system_clock::now() - start; std::vector v(size); std::fill(v.begin(), v.end(), 1.0); boost::chrono::duration trials_sec; for(unsigned long i = 0; i < trials; ++i) { boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); std::for_each(v.begin(), v.end(), add); trials_sec += boost::chrono::system_clock::now() - start; } profile::display(size, trials, sum, trials_sec.count(), decl_sec.count()); return 0; } ``` -------------------------------- ### Boost Local Function Operator Error Example Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/advanced_topics Demonstrates a compile-time error when attempting to name a local function as an operator using BOOST_LOCAL_FUNCTION_NAME. This highlights the restriction that local functions cannot be operators. ```cpp 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...`. ``` -------------------------------- ### Define and Use Local Function with Capture in C++ Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/transform This snippet demonstrates defining a local function `inc` that captures the `offset` variable and modifies its input `i`. It then uses `std::transform` to apply this local function to a vector. ```C++ // Copyright (C) 2009-2012 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/local_function #include #ifdef BOOST_NO_CXX11_VARIADIC_MACROS # error "variadic macros required" #else #include #include #include #include int main(void) { //[transform int offset = 5; std::vector v; std::vector w; for(int i = 1; i <= 2; ++i) v.push_back(i * 10); BOOST_TEST(v[0] == 10); BOOST_TEST(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_TEST(w[0] == 16); BOOST_TEST(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_TEST(v[0] == 27); BOOST_TEST(v[1] == 47); //] return boost::report_errors(); } #endif // VARIADIC_MACROS ``` -------------------------------- ### Example Usage of Non-Template Local Functions (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/same_line Illustrates the use of the `LOCAL_INC_DEC` macro in the `main` function. It defines local 'inc' and 'dec' functions capturing `delta` and tests their functionality by composing them. ```c++ int main(void) { int delta = 10; LOCAL_INC_DEC(delta) // Multiple local functions on same line. BOOST_TEST(dec(inc(123)) == 123); f(delta); return boost::report_errors(); } ``` -------------------------------- ### SCOPE_EXIT Macro Definition for Local Functions Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Macro that defines a scope exit using BOOST_LOCAL_FUNCTION with variable argument list. Enables binding of variables with const and reference qualifiers for scope cleanup operations. ```cpp #define SCOPE_EXIT(...) \ void BOOST_LOCAL_FUNCTION(__VA_ARGS__) ``` -------------------------------- ### Define Variadic Macro for Default Argument Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/add_with_default This snippet defines a preprocessor macro `WITH_DEFAULT` that expands to `, default`. This macro is used within the Boost.Local Function definition to specify a default value for a function parameter. ```c++ #define WITH_DEFAULT , default ``` -------------------------------- ### Declaring Local Functions in C++ Templates with Boost.LocalFunction Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/tutorial Demonstrates the basic syntax for declaring local functions within a C++ template context using the BOOST_LOCAL_FUNCTION_TPL and BOOST_LOCAL_FUNCTION_NAME_TPL macros. This approach is necessary when local functions are defined inside template code. ```C++ #include ... { ... _result-type_ BOOST_LOCAL_FUNCTION_TPL(_parameters_) { _body-code_ } BOOST_LOCAL_FUNCTION_NAME_TPL(_name_) ... } ``` -------------------------------- ### C++ Boost.Local Function with std::for_each Source: https://www.boost.org/doc/libs/latest/libs/local_function/example/profile_phoenix This C++ code demonstrates using Boost.Local Function's syntax (ref and arg_names) to define an in-place operation within std::for_each. It sums elements of a vector, multiplied by a factor, into a sum variable. Dependencies include Boost.Phoenix and Boost.Chrono. The input is a vector of doubles and an integer factor; the output is the calculated sum. ```cpp // Copyright (C) 2009-2012 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/local_function #include #include #include #include #include #include #include #include #include "profile_helpers.hpp" int main(int argc, char* argv[]) { unsigned long size = 0, trials = 0; profile::args(argc, argv, size, trials); double sum = 0.0; int factor = 1; std::vector v(size); std::fill(v.begin(), v.end(), 1.0); boost::chrono::duration trials_sec; for(unsigned long i = 0; i < trials; ++i) { boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); using boost::phoenix::ref; using boost::phoenix::arg_names::_1; std::for_each(v.begin(), v.end(), ( ref(sum) += factor * _1 )); trials_sec += boost::chrono::system_clock::now() - start; } profile::display(size, trials, sum, trials_sec.count()); return 0; } ``` -------------------------------- ### C++ Local Functor Manual Definition and Usage Source: https://www.boost.org/doc/libs/latest/libs/local_function/example/add_local_functor This C++ code demonstrates the manual definition of a local functor class named 'local_add'. It captures an integer reference 'sum' and a constant integer 'factor' to perform a calculation. The functor is then instantiated and used to process values, with the result verified using BOOST_TEST. ```C++ #include int main(void) { int sum = 0, factor = 10; struct local_add { // Unfortunately, boilerplate code to program the class. local_add(int& _sum, int _factor): sum(_sum), factor(_factor) {} inline void operator()(int num) { // Body uses C++ statement syntax. sum += factor * num; } private: // Unfortunately, cannot bind so repeat variable types. int& sum; // Access `sum` by reference. const int factor; // Make `factor` constant. } add(sum, factor); add(1); int nums[] = {2, 3}; // Unfortunately, cannot pass as template parameter to `std::for_each`. for(size_t i = 0; i < 2; ++i) add(nums[i]); BOOST_TEST(sum == 60); return boost::report_errors(); } ``` -------------------------------- ### Local Function with Only Const Binds (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/all_decl_seq This example illustrates local functions declared with only `const` binds. It demonstrates binding `const` references and values, including `this_` for class members. The local functions `l`, `t`, and `lt` are defined and called. ```C++ #include #include #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() struct s; BOOST_TYPEOF_REGISTER_TYPE(s); struct s { void f(double p = 1.23, double q = -1.23) { { int a, b; const int& BOOST_LOCAL_FUNCTION( (const bind a) (const bind& b) (const bind& p) (const bind q) ) { return b; } BOOST_LOCAL_FUNCTION_NAME(l) l(); const s& BOOST_LOCAL_FUNCTION( (const bind this_) ) { return *this_; } BOOST_LOCAL_FUNCTION_NAME(t) t(); const int BOOST_LOCAL_FUNCTION( (const bind a) (const bind& b) (const bind& p) (const bind q) (const bind this_) ) { return a; } BOOST_LOCAL_FUNCTION_NAME(lt) lt(); } } }; ``` -------------------------------- ### Define Local Function with Capture and Default Arguments (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/macro_commas_seq Demonstrates how to define a local function within `main` using the `BOOST_LOCAL_FUNCTION` macro. It shows how to specify captured variables, default values for arguments using `default`, and name the local function using `BOOST_LOCAL_FUNCTION_NAME`. Dependencies include Boost headers for local_function, identity_type, and typeof. ```cpp // Copyright (C) 2009-2012 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/local_function #include #include #include // Type-of registrations #include // needed for `NAME` macro. #include #include #include std::string cat(const std::string& x, const std::string& y) { return x + y; } template struct key_sizeof { static int const value; }; template int const key_sizeof::value = sizeof(K); typedef int sign_t; int main(void) { void BOOST_LOCAL_FUNCTION( (BOOST_IDENTITY_TYPE((const std::map&)) m) (BOOST_IDENTITY_TYPE((::sign_t)) sign) (const size_t& factor) (default (key_sizeof::value)) (const std::string& separator)(default cat(":", " ")) ) { // Do something... } BOOST_LOCAL_FUNCTION_NAME(f) std::map m; ::sign_t sign = -1; f(m, sign); return 0; } ``` -------------------------------- ### Recursive Local Functions in C++ Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/advanced_topics Enables a local function to call itself recursively. This is achieved by prefixing the function name with the 'recursive' keyword. The example demonstrates calculating factorials using a recursive local function within a class. ```cpp _result-type_ BOOST_LOCAL_FUNCTION(_parameters_) { ... // Body. } BOOST_LOCAL_FUNCTION_NAME(recursive _name_) // Recursive. struct calculator { std::vector results; void factorials(const std::vector& 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); } }; ``` -------------------------------- ### Test Local and Overloaded Functions with Boost.Test (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/test/overload_seq This code demonstrates how to use `BOOST_TEST` from `` to verify the correctness of the `add_s`, `add_d`, and the aggregated `add` overloaded function. It checks string concatenation, double addition with and without default arguments, and integer addition. ```cpp #include #include #include #include #include int add_i(int x, int y) { return x + y; } int main(void) { 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) , int (int, int) > add(add_s, add_d, add_d, add_i); BOOST_TEST(add("xyz") == "abcxyz"); BOOST_TEST((4.44 - add(3.21)) <= 0.001); // Equal within precision. BOOST_TEST((44.44 - add(3.21, 40.0)) <= 0.001); // Equal within precision. BOOST_TEST(add(1, 2) == 3); return boost::report_errors(); } ``` -------------------------------- ### SCOPE_EXIT_END Macro Implementation with PP Concatenation Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/examples Macro that completes scope exit definition by creating a local function name and instantiating scope_exit object. Uses Boost.Preprocessor for unique identifier generation to support multiple scope exits in same scope. ```cpp #define SCOPE_EXIT_END_(id) \ BOOST_LOCAL_FUNCTION_NAME(BOOST_PP_CAT(scope_exit_func_, id)) \ scope_exit BOOST_PP_CAT(scope_exit_, id)( \ BOOST_PP_CAT(scope_exit_func_, id)); ``` -------------------------------- ### Boost Local Function with WITH_DEFAULT Macro (C++) Source: https://www.boost.org/doc/libs/latest/libs/local_function/doc/html/boost_localfunction/advanced_topics Demonstrates an alternative syntax for default parameters in Boost C++ local functions using a 'WITH_DEFAULT' macro. This macro is defined to improve code readability by abstracting the 'default' keyword and comma separation. The example function 'add' also sets a default value of 2 for its second parameter 'y'. ```cpp #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_TEST(add(1) == 3); ```