在 C++11 lambdas 中使用 Boost 适配器

2021-12-23 00:00:00 lambda c++ c++11 boost boost-range

我试图编译这段代码:

#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <vector>

int main() {
    std::vector<int> v{
        1,5,4,2,8,5,3,7,9
    };
    std::cout << *boost::min_element(v | boost::adaptors::transformed(
            [](int i) { return -i; })) << std::endl;
    return 0;
}

编译失败并显示以下错误消息(经过很长的模板实例化小说):

The compilation failed with the following error message (after a long template instantiation novel):

/usr/local/include/boost/iterator/transform_iterator.hpp:84:26: error: use of deleted function ‘main()::<lambda(int)>::<lambda>()’
../main.cpp:12:5: error: a lambda closure type has a deleted default constructor

我用谷歌搜索了这个问题,发现 this 在 Boost Users 邮件列表存档中.它建议使用 #define BOOST_RESULT_OF_USE_DECLTYPE 可以解决问题.我把它放在代码的最开始,但它仍然无法编译.错误信息的长度似乎要短得多,但最后的错误信息是一样的.我目前使用的是 Boost 1.50.

I googled the problem, and found this in the Boost Users mailing list archive. It suggested that using #define BOOST_RESULT_OF_USE_DECLTYPE would solve the problem. I put it into the very beginning of my code, but it still doesn't compile. The length of the error message seems to be much shorter, but the error message at the end is the same. I'm currently using Boost 1.50.

这里有什么问题?有什么办法可以让这个工作吗?

What can be the problem here? Is there any way to make this work?

推荐答案

http://smellegantcode.wordpress.com/2011/10/31/linq-to-c-or-something-much-better/

但是你可以使用这个,效果很好.

But you can use this, that works well.

#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <vector>
#include <functional>

int main() {
    std::vector<int> v{
        1,5,4,2,8,5,3,7,9
    };
    std::function<int(int)> func = [](int i) { return -i; };
    std::cout << *boost::min_element(v | boost::adaptors::transformed(
    func)) << std::endl;
    return 0;
}

http://liveworkspace.org/code/b78b3f7d05049515ac207e0c12054c70

#define BOOST_RESULT_OF_USE_DECLTYPE 例如在 VS2012 中工作正常.

#define BOOST_RESULT_OF_USE_DECLTYPE works fine in VS2012 for example.

相关文章