Why can't compiler determine template of std::max with literal?

Deadly 提交于 2019-12-11 11:35:16

问题


Neither clang nor gcc, compile this:

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

giving some error of the flavor:

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

If I explicitly provide the template type, it works:

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

It's confusing because neither compiler complains with warnings if I compare size_t to 0, like it would if I compared size_t to int. Then I infer that the compiler can figure out that it makes sense to compare 0 to size_t, so what's stopping the compiler from figuring out which max to use?


回答1:


std::max only has one template argument, used for both parameters. When you call the function without explicitly specifying that argument, it tries to deduce it from both arguments, ends up with size_t for one deduction and int for the other (because those are the types of the two arguments) and doesn't know which one you want.

Pretty sure the part of Clang's error message after the place you cut off says exactly that, though.




回答2:


The litwral is of type int. The template matching (T, T) won't do conversions.



来源:https://stackoverflow.com/questions/27004024/why-cant-compiler-determine-template-of-stdmax-with-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!