为什么编译器无法用文字确定std :: max的模板?

Ale*_*son 1 c++ templates stl overloading compiler-errors

clang和gcc都不编译:

#include <algorithm>
int main()
{
  size_t t = 1;
  t = std::max(t,0);
}
Run Code Online (Sandbox Code Playgroud)

给出一些风味的错误:

error: no matching function for call to 'max(size_t&,int)'
... note:   template argument deduction/substitution failed:
Run Code Online (Sandbox Code Playgroud)

如果我明确提供模板类型,它的工作原理如下:

#include <algorithm>
int main()
{
  size_t t = 1;
  t = std::max<size_t>(t,0);
}
Run Code Online (Sandbox Code Playgroud)

这是令人困惑,因为没有编译器警告抱怨,如果我比size_t来0,喜欢它想如果我比size_t对int.然后,我推断,编译器可以弄清楚,是有意义的比较0来size_t,那么是什么阻止来自搞清楚,编译器max使用?

Seb*_*edl 5

std::max只有一个模板参数,用于两个参数.当您在没有明确指定该参数的情况下调用该函数时,它会尝试从两个参数中推导出它,最终size_t得到一个推论而int另一个(因为那些是两个参数的类型)并且不知道您想要哪个.

很确定Clang在你切断的地方之后的错误信息部分说明了这一点.