我想用带init捕获的Boost.Range和C++1y lambdas来计算两个矢量在元素上的差值。减去一个向量的固定(即第一个)元素的更简单的情况是可行的。但是,当我试图通过在第二个范围内增加迭代器(并使lambda 可变的)来计算“向量化差”时,我会得到一个编译器错误。示例代码(请注意,我没有使用通用的lambdas,以便g++ 4.8和Clang都可以解析这段代码):
#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。在这里,g++和Clang都抱怨
在'boost::mpl::eval_if,boost::result_of]::__lambda1(const int&)>中没有名为' type‘的类型,boost::mpl::identity >::f_ {aka struct boost::result_of]::__lambda1(const int&)>}’typedef type named f_::type type;
问题:怎么回事?
发布于 2014-02-12 10:18:02
只是闭包类型没有boost::mpl显然需要的嵌套类型防御。如果将lambda表达式转换为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
复制相似问题