Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop automatic conversion from int to float and vice-versa in std::map

I wrote a small program of using std::map here as follows.

int main()
{
  map<int,float>m1;
  m1.insert(pair<int,float>(10,15.0));   //step-1
  m1.insert(pair<float,int>(12.0,13));   //step-2
  cout<<"map size="<<m1.size()<<endl;    //step -3

I created a map with int type as key and float type as value(key-value) pair for the map m1

  1. Created a normal int-float pair and inserted to map.

  2. Created a cross float-int pair and inserted to map. Now I know that implicit conversion is making this pair to get inserted to map.

Here I just don't want the implicit conversion to take place and compiler error should be given.

What sort of changes I have to do in this program/map to make the comipiler flag an error while we try to do step-2 type operation?

like image 223
Santosh Sahu Avatar asked Sep 12 '14 13:09

Santosh Sahu


1 Answers

Here's a suggestion:

template <typename K, typename V, typename W>
void map_insert(map<K,V>& m, K k, W w) {
  V v = w;
  m.insert(pair<K,V>(k,v));
}

int main() {
  map<int,float>m1;
  map_insert(m1, 10, 15.0);
  map_insert(m1, 12.0, 13);  // compiler complains here
  cout<<"map size="<<m1.size()<<endl;

The third template parameter is a bit awkward but is necessary to allow casting from double to float.

like image 100
dshin Avatar answered Sep 27 '22 19:09

dshin