boost转换迭代器和c ++ 11 lambda

Nit*_*hin 12 c++ boost c++11 boost-range

我试图通过向适配器提供c ++ 0x lambda来使用boost :: adapters :: transformed.

以下代码无法编译.我正在使用g ++ 4.6.2和boost 1.48.

#include <iostream>
#include <vector>

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

using namespace std;
namespace br    = boost::range;
namespace badpt = boost::adaptors;


int main()
{  
  vector<int> a = {0,3,1,};
  vector<int> b = {100,200,300,400};

  auto my_ftor = [&b](int r)->int{return b[r];};

  cout<<*br::max_element(a|badpt::transformed(my_ftor))<<endl;
}
Run Code Online (Sandbox Code Playgroud)

关于我在这里做错了什么的想法?

For*_*veR 8

这是众所周知的问题.看这里

http://boost.2283326.n4.nabble.com/range-cannot-use-lambda-predicate-in-adaptor-with-certain-algorithms-td3560157.html

不久,你应该使用这个宏

#define BOOST_RESULT_OF_USE_DECLTYPE
Run Code Online (Sandbox Code Playgroud)

用来decltype代替boost::result_of.

这里引用

如果您的编译器支持decltype,那么您可以通过定义宏BOOST_RESULT_OF_USE_DECLTYPE来启用自动结果类型推导,如下例所示.


Pau*_* II 4

好吧,lambda 表现不佳,因为它们不可默认构造,而这对于迭代器来说是必需的。这是我用于 lambda 的包装器:

#define RETURNS(...) -> decltype(__VA_ARGS__) { return (__VA_ARGS__); }

template<class Fun>
struct function_object
{
    boost::optional<Fun> f;

    function_object()
    {}
    function_object(Fun f): f(f)
    {}

    function_object(const function_object & rhs) : f(rhs.f)
    {}

    // Assignment operator is just a copy construction, which does not provide
    // the strong exception guarantee.
    function_object& operator=(const function_object& rhs)
    {
        if (this != &rhs)
        {
            this->~function_object();
            new (this) function_object(rhs);
        }
        return *this;
    }

    template<class F>
    struct result
    {};

    template<class F, class T>
    struct result<F(T)>
    {
        typedef decltype(std::declval<Fun>()(std::declval<T>())) type;
    };

    template<class T>
    auto operator()(T && x) const RETURNS((*f)(std::forward<T>(x)))

    template<class T>
    auto operator()(T && x) RETURNS((*f)(std::forward<T>(x)))
};

template<class F>
function_object<F> make_function_object(F f)
{
    return function_object<F>(f);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

int main()
{  
  vector<int> a = {0,3,1,};
  vector<int> b = {100,200,300,400};

  cout<<*br::max_element(a|badpt::transformed(make_function_object([&b](int r)->int{return b[r];};)))<<endl;
}
Run Code Online (Sandbox Code Playgroud)