版权所有 © 2009-2012 Lorenzo Caminiti
根据 Boost 软件许可证版本 1.0 分发(参见附带文件 LICENSE_1_0.txt 或副本位于 https://boost.ac.cn/LICENSE_1_0.txt)
此库允许在其他函数内部、以及直接在需要它们的范围内编写局部函数。
局部函数(又名 嵌套函数)是一种 信息隐藏 的形式,它们有助于将过程式任务分解为仅在局部有意义的子任务,从而避免程序其他部分因不相关的函数、变量等而显得杂乱。因此,局部函数可以与其他结构化可能性(如命名空间和类)相辅相成。局部函数是许多编程语言(尤其是 Pascal 和 Ada)的特性,但 C++03 却缺少(另见 [N2511])。
使用 C++11 lambda 函数,可以通过命名 lambda 函数并将其赋值给局部变量来实现局部函数。例如(另见 add_cxx11_lambda.cpp)
int main(void) { // Some local scope. int sum = 0, factor = 10; // Variables in scope to bind. auto add = [factor, &sum](int num) { // C++11 only. sum += factor * num; }; add(1); // Call the lambda. 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(); }
此库允许在 C++03 和 C++11 之间可移植地编写局部函数(并且在 C++11 编译器上的性能与 lambda 函数相当)。例如(另见 add.cpp)
int main(void) { // Some local scope. int sum = 0, factor = 10; // Variables in scope to bind. 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(); }
此库为局部函数支持以下特性:
有关此库、 C++11 lambda 函数、 Boost.Phoenix 以及其他实现与局部函数相关功能的 C++ 技术之间的比较,请参阅 备选方案 部分。