Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ warning options for casting pair?

Tags:

c++

g++

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?

like image 958
chtlp Avatar asked Mar 30 '12 11:03

chtlp


1 Answers

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);
like image 130
Kerrek SB Avatar answered Sep 30 '22 05:09

Kerrek SB