首页 > 解决方案 > 使用算术将 boost 占位符转换为 std

问题描述

我正在转换一个使用 boost 和占位符来转换现有逻辑的地图的 C++ 项目:

inline const std::vector<uint32_t> average(const std::pair<uint16_t, std::vector<uint32_t> >& left,
                                           const std::pair<uint16_t, std::vector<uint32_t> >& right)
{
    // Ejector rates should be symmetrical
    assert(left.second.size() == right.second.size());
    std::vector<uint32_t> result;
    result.reserve(left.second.size());
    namespace bl = boost::lambda;
    // Walk both, do funny thing with each element in turn. Stuff into result.
    std::transform(left.second.begin(), left.second.end(), right.second.begin(), std::back_inserter(result), (bl::_1 + bl::_2) / 2);
    return result;
}

我想用 std 替换 boost 引用:

inline const std::vector<uint32_t> average(const std::pair<uint16_t, std::vector<uint32_t> >& left,
                                           const std::pair<uint16_t, std::vector<uint32_t> >& right)
{
    // Ejector rates should be symmetrical
    assert(left.second.size() == right.second.size());
    std::vector<uint32_t> result;
    result.reserve(left.second.size());
    namespace bl = boost::lambda;
    // Walk both, do funny thing with each element in turn. Stuff into result.
    std::transform(left.second.begin(), left.second.end(), right.second.begin(), std::back_inserter(result),
        (std::placeholders::_1 + std::placeholders::_2) / 2);
    return result;
}

我越来越:

error C2784: 'std::_Deque_const_iterator<_Mydeque> std::operator +(_Deque_const_iterator<_Mydeque>::difference_type,std::_Deque_const_iterator<_Mydeque>)' : could not deduce template argument for 'std::_Deque_const_iterator<_Mydeque>' from 'std::_Ph<2>'
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\deque(555) : see declaration of 'std::operator +'

在包含以下内容的行上:

(std::placeholders::_1 + std::placeholders::_2) / 2);

这样做的正确方法是什么?

标签: c++booststdplaceholder

解决方案


使用 lambda。

std::transform(left.second.begin(), left.second.end(), right.second.begin(), std::back_inserter(result),
        [](auto a, auto b){ return (a + b) / 2; });

推荐阅读