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
>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);
}
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.