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使用非常簡單,官方示例代碼如下:
main() {
sum = , factor = ;
BOOST_LOCAL_FUNCTION( bind factor, bind& sum, sum += factor *
add();
nums[] = {, std::for_each(nums, nums + , add);
BOOST_TEST(sum == );
}