Anton Kulev
Anton Kulev

Reputation: 162

Strange usage of std::map constructor

I searched for an implementation of std::map runtime ordering and have found this solution: STL std::map dynamic ordering

It is clear for me, but I don't understand, how it can be possible to use OrderingType in the constructor of std::map. std::map has a constructor, which gets a comparator object as an argument. So it is normal from my point of view to use code like this:

int main()
{
   Ordering<int> test_ordering( ASCENDING );   
   CUSTOMMAP map1( test_ordering );

   return 0;
}

But code from above mentioned topic also compiles:

int main()
{
   CUSTOMMAP map1( ASCENDING );
   //...
   return 0;
}

I don't understand, why it works: constructor of std::map must not get argument of OrderingType enumeration instead of Ordering class object itself.

Upvotes: 3

Views: 171

Answers (1)

John Calsbeek
John Calsbeek

Reputation: 36497

If the constructor on Ordering<int> that takes your enumeration isn't declared as explicit, then it is considered a "conversion constructor" that can automatically be inserted when the compiler has a need to convert from your enumeration type to the Ordering<int> type. So the compiler is effectively taking this:

CUSTOMMAP map1( ASCENDING );

and transforming it into this:

CUSTOMMAP map1( Ordering<int>(ASCENDING) );

This is called an implicit conversion.

Upvotes: 9

Related Questions