【问题标题】:Conversion from _Ty to int warning in MSVC accumulateMSVC 中从 _Ty 到 int 警告的转换累积
【发布时间】:2020-09-23 02:14:17
【问题描述】:

我将 MSVC 警告提高到 4 级,但在使用累积 over boost::circular_buffer 时遇到问题。这段代码:

boost::circular_buffer<unsigned short> shorts;
shorts.resize(10);
unsigned short res = std::accumulate(shorts.begin(), shorts.end(), static_cast<unsigned short>(0));

在累积模板中失败并出现possible loss of data 警告(数字):

// FUNCTION TEMPLATE accumulate
template<class _InIt,
    class _Ty,
    class _Fn>
    _NODISCARD inline _Ty accumulate(const _InIt _First, const _InIt _Last, _Ty _Val, _Fn _Reduce_op)
    {   // return noncommutative and nonassociative reduction of _Val and all in [_First, _Last), using _Reduce_op
    _Adl_verify_range(_First, _Last);
    auto _UFirst = _Get_unwrapped(_First);
    const auto _ULast = _Get_unwrapped(_Last);
    for (; _UFirst != _ULast; ++_UFirst)
        {
        _Val = _Reduce_op(_Val, *_UFirst); // <-- THIS IS WHERE THE WARNING IS
        }

    return (_Val);
    }

有什么想法可能是错的吗?

【问题讨论】:

    标签: c++ visual-c++ boost


    【解决方案1】:

    25.9.2 Accumulate [accumulate]std::accumulate 的效果定义为acc = std::move(acc) + *i。由于 C++ 出于某种原因不支持小于int 的整数类型的算术运算,而是在求和之前将+ 两边的参数提升为int,结果将是int。因此,您会在此处收到看似不可避免的警告。

    一种可能的解决方法是将累加器定义为unsinged int,然后将最终结果转换为所需的类型:

    unsigned short res{static_cast< unsigned short >(::std::accumulate(shorts.begin(), shorts.end(), 0u));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-04
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多