towi towi - 1 year ago 125
C++ Question

Using conversion operator to initialize a map

What is preventing this initialization to work?

#include <map>
using std::map; using std::pair; using std::make_pair;
struct P {
char a_, b_;
P(char a, char b) : a_{a}, b_{b} {}
operator pair<char,char>() { return make_pair(a_, b_); }
int main() {
map<char,char> qmap { P( 'a','b' ) };

It looks like the conversion operator in
can not be applied implicitly inside a braced-initialisier-list? Or is it something else?

Answer Source

It can, but you forgot the key point: map's value_type is actually pair<const Key, Value>, so in your example you'd need two conversions (Ppair<char, char>pair<char const, char>) to meet your qmap's value_type. This is one more conversion that the rules allow.

If you change your conversion operator to

operator pair<char const,char>() { return make_pair(a_, b_); }

your code compiles.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download