问题
I want to compute the element-wise difference of two vectors using Boost.Range and C++1y lambdas with init-capture. The simpler case of subtracting a fixed (i.e. the first) element of one vector works. However, when I try to compute the "vectorized difference" by increasing the iterator over the second range (and making the lambda mutable), I get a compiler error. Sample code (note that I didn't use generalized lambdas so that both g++ 4.8 and Clang SVN can parse this code):
#include <iostream>
#include <iterator>
#include <vector>
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
template<class R>
auto delta_beg(R const& rng1, R const& rng2)
{
using Elem = typename R::value_type;
return rng1 | boost::adaptors::transformed(
[first2 = begin(rng2)](Elem const& e) {
return e - *first2;
});
}
template<class R>
auto delta_rng(R const& rng1, R const& rng2)
{
using Elem = typename R::value_type;
return rng1 | boost::adaptors::transformed(
[first2 = begin(rng2)](Elem const& e) mutable {
return e - *first2++;
});
}
int main()
{
auto r1 = std::vector<int>{ 8, 10, 12, 15 };
auto r2 = std::vector<int>{ 1, 2, 9, 13 };
// prints 7, 9, 11, 14
boost::copy(delta_beg(r1, r2), std::ostream_iterator<int>(std::cout, ",")); std::cout << "\n";
// ERROR, should print 7, 8, 3, 2
boost::copy(delta_rng(r1, r2), std::ostream_iterator<int>(std::cout, ",")); std::cout << "\n";
}
Live Example. Here both g++ and Clang complain about
no type named 'type' in 'boost::mpl::eval_if, boost::result_of]::__lambda1(const int&)>, boost::mpl::identity >::f_ {aka struct boost::result_of]::__lambda1(const int&)>}' typedef typename f_::type type;
Question: what is going on?
回答1:
It's just that closure-types don't have nested typedefs that boost::mpl
apparently requires. It works if you convert the lambda expression to std::function
:
#include <iostream>
#include <iterator>
#include <vector>
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
template<class R>
auto delta_beg(R const& rng1, R const& rng2)
{
using Elem = typename R::value_type;
std::function<Elem(Elem const&)> f =
[first2 = begin(rng2)](Elem const& e) { return e - *first2; };
return rng1 | boost::adaptors::transformed(f);
}
template<class R>
auto delta_rng(R const& rng1, R const& rng2)
{
using Elem = typename R::value_type;
std::function<Elem(Elem const&)> f =
[first2 = begin(rng2)](Elem const& e) mutable { return e - *first2++; };
return rng1 | boost::adaptors::transformed(f);
}
int main()
{
auto r1 = std::vector<int>{ 8, 10, 12, 15 };
auto r2 = std::vector<int>{ 1, 2, 9, 13 };
// prints 7, 9, 11, 14
boost::copy(delta_beg(r1, r2), std::ostream_iterator<int>(std::cout, ",")); std::cout << "\n";
// ERROR, should print 7, 8, 3, 2
boost::copy(delta_rng(r1, r2), std::ostream_iterator<int>(std::cout, ",")); std::cout << "\n";
}
Live demo.
来源:https://stackoverflow.com/questions/21724760/boost-range-not-working-with-c1y-init-capture-mutable-lambda