Overloaded Template Resolution

The following code prints "First." Why is the first template selected, while the second seems to be more specialized and should be better combined? (I am using MSVC10)

I understand that this has something to do with the fact that the second template accepts its const & argument, but still cannot understand why this makes it worse.

 #include <map> #include <iostream> template<class Range> void go(Range &r) { std::cout << "First" << std::endl; } template<class K, class V> void go(const std::map<K, V> &m) { std::cout << "Second" << std::endl; } int main() { std::map<int, int> m; go(m); } 
+4
source share
1 answer

The compiler creates the first template for

 void go(std::map<int, int>& r) 

and second -

 void go(const std::map<int, int>& m) 

The conversion sequence for the first is an identity transformation: nothing needs to be done, the lvalue argument is bound directly to the link.

The conversion sequence for the second is a qualifier conversion: the lvalue argument needs a constant added to bind to the link.

So the first is the best match. If the variable in main was const, the second would be better, as you can see here , because then the two templates create the same thing, and only then the concept of "more specialized" comes into play.

+13
source

Source: https://habr.com/ru/post/1492963/


All Articles