【boost】BOOST_LOCAL_FUNCTION体验

时间:2023-01-16 10:34:51

c++11里支持使用lambda在函数内定义本地嵌套函数,将一些算法的判断式定义为本地函数可以使代码更加清晰,同时声明和调用靠近也使得更容易维护。遗憾的是公司开发平台任然停留在vs2008,使用boost库的lambda表达式来模拟实在是有些笨拙与晦涩。

偶然在论坛上看见boost1.50版本后引入了BOOST_LOCAL_FUNCTION宏,官方简介如下:

http://www.boost.org/doc/libs/1_54_0/libs/local_function/doc/html/boost_localfunction/tutorial.html

Local functions are defined using macros from the header file boost/local_function.hpp. The macros must be used from within a declarative context (this is a limitation with respect to C++11 lambda functions which can instead be declared also within expressions):

#include <boost/local_function.hpp> // This library header.

...
{ // Some declarative context.
...
result-type BOOST_LOCAL_FUNCTION(parameters) {
body-code
} BOOST_LOCAL_FUNCTION_NAME(name)
...
}

使用宏的方式来定义了一个嵌套的函数(虽然只是看起来像),但是也使得我们有另一种选择。BOOST_LOCAL_FUNCTION使用非常简单,官方示例代码如下:
 int main(void) {                            // Some local scope.
int sum = , factor = ; // 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(); // Call the local function.
int nums[] = {, };
std::for_each(nums, nums + , add); // Pass it to an algorithm. BOOST_TEST(sum == ); // Assert final summation value.
return boost::report_errors();
}