Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion warnings for std::copy and std::vector::assign

Tags:

When a floating point number is inserted into a std::vector<int>, the number must be converted by some kind of rounding. Typically this changes the number, 1.5 is changed to 1 or 2, and I would expect the compiler at least to warn about this conversion. So I use the -Wconversion flag on g++ or clang++. This enables warnings for std::vector::push_back or direct assignment, but not for std::copy or std::vector::assign(iterator first, iterator end).

Now my question is: How do I get conversion warnings for std::copy and std::vector::assign?

Here is my example program:

#include <iostream>
#include <vector>
#include <algorithm>

using source_type = std::vector<double>;
using target_type = std::vector<int>;

int main() {
    source_type vsource;
    target_type vtarget1;
    target_type vtarget2;
    target_type vtarget3;
    target_type vtarget4;

    // Fill source with a number
    vsource.push_back(1.5);

    // This will give a compiler warning as expected
    vtarget1.push_back(vsource.at(0));

    // This does not give a warning, why not?
    vtarget2.assign(vsource.begin(), vsource.end());

    // Also this does not give a warning, why not?
    vtarget3.assign(vsource.size(), 0);
    std::copy(vsource.begin(), vsource.end(), vtarget3.begin());


    // The following should be equivalent to std::copy according to
    // http://www.cplusplus.com/reference/algorithm/copy/?kw=copy
    // Here we get a warning as expected (in contrast to std::copy).
    vtarget4.assign(vsource.size(), 0);
    auto source = vsource.begin();
    auto target = vtarget4.begin();
    while (source != vsource.end()) {
       *target = *source;
       ++target; ++source;
    }

    std::cout << vsource.at(0)  << " "
              << vtarget1.at(0) << " "
              << vtarget2.at(0) << " "
              << vtarget3.at(0) << " "
              << vtarget4.at(0) << std::endl;

    return 0;
}

I compile with:

g++ -Wall -Wextra -Wconversion -std=c++11 -pedantic 
clang++ -Wall -Wextra -Wconversion -std=c++11 -pedantic

I only get two warnings, I want to have a few more:

question.cpp:22:24: warning: implicit conversion turns floating-point number into integer: 'value_type' (aka 'double')
      to 'value_type' (aka 'int') [-Wfloat-conversion]
    vtarget1.push_back(vsource.at(0));

question.cpp:40:18: warning: implicit conversion turns floating-point number into integer: 'double' to 'int'
      [-Wfloat-conversion]
       *target = *source;