隐式地将lambda转换为boost::函数

implicitly converting lambda to boost::function

本文关键字:boost 转换 函数 lambda      更新时间:2023-10-16

我试图通过以下代码使隐式lambda转换为lambda函数:

#include <boost/function.hpp>
struct Bla {
};
struct Foo {
boost::function< void(Bla& )> f;
  template <typename FnType>
  Foo( FnType fn) : f(fn) {}
};
#include <iostream>
int main() {
Bla bla;
Foo f( [](Bla& v) -> { std::cout << " inside lambda " << std::endl; } );
};

然而,我得到这个错误与g++

$ g++ --version
g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
$ g++ -std=c++0x test.cpp `pkg-config --cflags boost-1.46` -o xtest `pkg-config --libs boost-1.46` 
test.cpp: In function ‘int main()’:
test.cpp:21: error: expected primary-expression before ‘[’ token
test.cpp:21: error: expected primary-expression before ‘]’ token
test.cpp:21: error: expected primary-expression before ‘&’ token
test.cpp:21: error: ‘v’ was not declared in this scope
test.cpp:21: error: expected unqualified-id before ‘{’ token

你知道我怎样才能实现上述目标吗?或者我能不能做到?


UPDATE try with g++ 4.5

$ g++-4.5 --version
g++-4.5 (Ubuntu/Linaro 4.5.1-7ubuntu2) 4.5.1
$ g++-4.5 -std=c++0x test.cpp `pkg-config --cflags boost-1.46` -o xtest `pkg-config --libs boost-1.46` 
test.cpp: In function ‘int main()’:
test.cpp:20:22: error: expected type-specifier before ‘{’ token

您缺少一个void:

Foo f( [](Bla& v) -> void { std::cout << " inside lambda " << std::endl; } );
//                   ^ here

或者,正如@ildjarn指出的,您可以简单地省略返回类型:

Foo f( [](Bla& v) { std::cout << " inside lambda " << std::endl; } );

使用这两行代码中的任何一行,您的代码都可以很好地使用mingwg++ 4.5.2和Boost v1.46.1编译。

您的lambda语法错误。这里有'->'但没有指定返回类型。你的意思可能是:

Foo f( [](Bla& v) { std::cout << " inside lambda " << std::endl; } );