为什么编译器无法用文字确定std :: max的模板? [英] Why can't compiler determine template of std::max with literal?

查看:119
本文介绍了为什么编译器无法用文字确定std :: max的模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既不是clang也不是gcc,请对此进行编译:

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);
}

这令人困惑,因为如果我比较 size_t 到 0 ,就像我将 size_t 到<$ c $进行比较一样c> int 。然后,我推断出编译器可以弄清楚将 0 size_t 进行比较是有意义的,那么是什么阻止了编译器从弄清楚要使用哪个 max

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?

推荐答案

std :: max 只有一个模板参数,用于两个参数。当您在未显式指定该参数的情况下调用该函数时,它将尝试从两个参数推导出该函数,最终以 size_t 进行一次推导,并以 int结束作为另一个参数(因为这是两个参数的类型),并且不知道您要哪个。

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.

很确定Clang的一部分但是,您切断的地方后面出现了一条错误消息,确切地说。

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

这篇关于为什么编译器无法用文字确定std :: max的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆