0

I was playing around with std::vector initialization when I was kind of surprised to discover that I can "transparently" initialize a std::vector of doubles from a std::vector of floats. This also works with std::vector::insert.

#include <vector>

// fmt library
#define FMT_HEADER_ONLY
#include <fmt/core.h>
#include <fmt/ranges.h>

int main() {

    std::vector<float> f_v = { 1, 2, 3 };
    std::vector<double> d_v = std::vector<double>(std::begin(f_v), std::end(f_v));
    d_v.insert(std::end(d_v), std::begin(f_v), std::end(f_v));
    fmt::print("{}\n", d_v);

    float f_a[] = {1, 2, 3};
    std::vector<double> d_a = std::vector<double>(f_a, f_a + 3);
    d_a.insert(std::end(d_a), f_a, f_a + 3);
    fmt::print("{}\n", d_a);
}

Am I overlooking something or is it really that easy?

Filippo Bistaffa
  • 551
  • 3
  • 16
  • The fact that you can losslessly promote a `float` to a `double` seems reasonable. Same reason you can trivially do something like `double x{0.1F};` without any problems. – Mad Physicist Mar 08 '23 at 22:16
  • 1
    This is no different than `std::vector` and assigning it `uint32_t`'s. – PaulMcKenzie Mar 08 '23 at 22:17
  • Now try to do it the other way around and see what the compiler tells you. Should be a warning at least. – Mad Physicist Mar 08 '23 at 22:17
  • 3
    Methods that take a pair of iterators would happily covert from the iterator's value type to the element type (assuming one is implicitly convertible to the other, of course; you'll get a compiler error otherwise). – Igor Tandetnik Mar 08 '23 at 22:18
  • 1
    @MadPhysicist I tried that and I got no warning whatsoever with `g++` even with `-pedantic-errors -Wall -Wextra -pedantic`. – Filippo Bistaffa Mar 08 '23 at 22:21
  • Interesting. I guess the truncation is done silently. Seems odd though. – Mad Physicist Mar 08 '23 at 22:22
  • @MadPhysicist GCC has some warnings disabled by default even when `-Wall`, `-Wextra`, and `-pedantic` are specified. To warn in case of a `double` to `float` conversion when constructing a vector using a range, you can enable `-Wconversion` and `-Wsystem-headers` options. See https://godbolt.org/z/9KhzWE38s for an example (scroll to the end of the warning message there to see the actual warning). – heap underrun Mar 09 '23 at 00:39

0 Answers0