【问题标题】:double to int conversion warning in std::accumulatestd::accumulate 中的 double 到 int 转换警告
【发布时间】:2023-03-06 20:38:01
【问题描述】:

如何强制 gcc/clang 在此类代码中显示关于将 double 转换为 int 的警告(特别是在使用 std::accumulate 用于双精度容器但结果为整数时):

#include <iostream>
#include <numeric>
#include <vector>

int main() {

    std::vector<double> v = { 0.5, 0.6, 0.7 };

    // gives wrong result due integer initial value
    std::cout << std::accumulate( v.begin(), v.end(), 0 ) << std::endl; // no warning

    int i = 4.2; // warning

    return 0;
}

-Wconversion 不能正常工作。链接:http://goo.gl/efJUou

附: VS2013在模板函数中报类型推导警告,您可以通过它来捕捉错误。

【问题讨论】:

    标签: c++ type-conversion compiler-warnings


    【解决方案1】:

    默认情况下,系统标头禁用警告。您可以使用选项-Wsystem-headers 来启用它们,但缺点是它会输出额外的不相关警告。

    【讨论】:

    • 如果我能对否决票做出解释,将不胜感激。
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2015-08-30
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多