c + +11 Lane supports the use of lambda function defined in a local nested functions , some of the algorithms determine the type defined as a local function can make the code clearer, while declaring and calling also makes it easier to maintain close . Unfortunately, any natural development platform company stays in vs2008, use the boost library to simulate a lambda expression is a bit clumsy and obscure .
occasionally seen on the forum boost1.50 version introduces BOOST_LOCAL_FUNCTION macro , the official described as follows :
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使用非常简单,官方示例代码如下:
1 int main(void) { // Some local scope.
2 int sum = 0, factor = 10; // Variables in scope to bind.
3
4 void BOOST_LOCAL_FUNCTION(const bind factor, bind& sum, int num) {
5 sum += factor * num;
6 } BOOST_LOCAL_FUNCTION_NAME(add)
7
8 add(1); // Call the local function.
9 int nums[] = {2, 3};
10 std::for_each(nums, nums + 2, add); // Pass it to an algorithm.
11
12 BOOST_TEST(sum == 60); // Assert final summation value.
13 return boost::report_errors();
14 }
没有评论:
发表评论