Alex Rivera | Logout

g++ warning options for casting pair?

Asked 2012-03-30T11:49:59.940
8

I just found that C++ doesn't give any warnings for casting from pair<double, int> to pair<int, int>, which is a little surprising. Here is my program test_pair.cpp:

#include <vector>
#include <utility>
using namespace std;


int main()
{
    std::vector<pair<int, int> > v;
    pair<double, int> p = make_pair(3.8, 3);
    v.push_back(p);                                                           
}

I compile it using g++ test_type.cpp -Wall -Wconversion, but still no warnings are generated. I am using g++ v4.6.1. Anyone got any idea how to make g++ generate a warning for this, or it just can't be done?

Edit
Report

1 Answer

4

Pairs (and tuples) are constructible from almost anything that fits. In particular, each element can be constructed from anything that's implicitly convertible to it. Basically, it "does what you expect". The pair has constructor templates that look something like this:

template <typename U, typename V>
pair(U && u, V && v) : first(std::forward<U>(u)), second(std::forward<V>(v))
{ }

However, you should just say:

v.emplace_back(3.8, 3);
answered 2012-03-30T11:53:21.123

Your Answer