Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to Insert a key value pair into a map using implicit converter of a arbitrary data struct?

I have the following code:

#include <map>
#include <iostream>

struct keyValue
 {
    int key{0};
    int value {0};

    operator std::pair<int, int>()
    {
        return {key, value};
    }
 };

 void foo(const std::pair<int, int>& pa)
 {
    std::cout << pa.first << std::endl;
    std::cout << pa.second<< std::endl;
 }

 int main ()
 {
    keyValue kv {1,10};
    std::map <int, int> map{};
    foo(kv);
   // map.insert(kv);
    return 0;
 }

The struct has an implicit conversion operator to std::pair,
The implicit converter seems to work fine when calling the function for example.
But as soon as I try to call insert or emplace interfaces of the map I get the compilation
error of finding no matching function. Could any one please point out the problem and if it is possible to insert to the map using custom implicit convertor operator at all.
compiler explorer

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Keys in std::map are const, elements of std::map<int,int> are std::pair<const int,int>.

#include <map>
#include <iostream>
struct keyValue
 {
    int key{0};
    int value {0};

    operator std::pair<const int, int>()
    {
        return {key, value};
    }
 };


 int main ()
 {
    keyValue kv {1,10};
    std::map <int, int> map{};
    map.insert(kv);
 }

Live Demo.

However, implicit conversions are strongly discouraged. You pay the price for a convenient map.insert(kv) instead of a map.insert(kv.get_key_value_pair()) back double and triple for confusing bugs caused by the conversion.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading