2
#include <iostream>


int min(int a, int b){
    return a < b ? a : b;
}

long long min(long long a, long long b){
    return a < b ? a : b;
}

int main(){
    int a = 1;
    long long b = 2;
    std::cout<<min(a, b);
    return 0;
}

Compile error:

test.cpp: In function ‘int main()’: test.cpp:15:19: error: call of overloaded ‘min(int&, long long int&)’ is ambiguous cout<

But why the long long min(long long a, long long b) is not inferred automatically?

Auto cast int a to long long a would not make it worse at all?


#include <iostream>

long long min(long long a, long long b){
    return a < b ? a : b;
}

int main(){
    int a = 1;
    long long b = 2;
    std::cout<<min(a, b);
    return 0;
}

This one will work without compiling error.


#include <iostream>
#include <algorithm>
#include <functional>

int main(){
    int a = 1;
    long long b = 2;
    std::cout<<std::min(a, b);
    return 0;
}

In file included from /usr/include/c++/4.8/algorithm:62:0, from test.cpp:2: /usr/include/c++/4.8/bits/stl_algo.h:4226:5: note: template _Tp std::min(std::initializer_list<_Tp>, _Compare) min(initializer_list<_Tp> __l, _Compare __comp) ^ /usr/include/c++/4.8/bits/stl_algo.h:4226:5: note: template argument deduction/substitution failed: test.cpp:8:29: note:
mismatched types ‘std::initializer_list<_Tp>’ and ‘int’ std::cout<

Kamel
  • 1,856
  • 1
  • 15
  • 25
  • 4
    Whatever you do, [don't say `using namespace std`](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). I wonder who teaches people that. – juanchopanza Aug 11 '15 at 07:02
  • 1
    Past integral promotions, all integral conversions are one "rule". That's just how it is. – chris Aug 11 '15 at 07:12
  • **Template it.** It'll make your problems go away. :) – CodeAngry Aug 11 '15 at 07:27
  • Why even the `std::min` fails as well? – Kamel Aug 11 '15 at 07:30
  • 1
    @Kamel, this may be helpful: [error: no matching function for call to ‘min(long unsigned int&, unsigned int&)’](http://stackoverflow.com/questions/14508022/error-no-matching-function-for-call-to-minlong-unsigned-int-unsigned-int) – awesoon Aug 11 '15 at 07:33
  • 1
    @Kamel, Template argument deduction doesn't take conversions into account. One template parameter can't match two types. – chris Aug 11 '15 at 07:35

0 Answers0