将带算术的 boost 占位符转换为 std

Conversion of boost placeholders with arithmetic to std

我正在转换一个 C++ 项目,该项目使用 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), (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);

正确的做法是什么?

使用 lambda。

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

只需使用 lambda。 在一般情况下,您可以使用 const auto refs 来避免处理参数:

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

对于像 int 这样的小数字类型,您可以按值传递它们并仅使用 const auto 或明确指定类型:

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