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

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

问题描述

无论是 clang 还是 gcc,编译这个:

Neither clang nor gcc, compile this:

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

给出一些味道的错误:

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_t0 进行比较,编译器都不会抱怨警告,就像我将 size_t 进行比较一样整数.然后我推断编译器可以确定将 0size_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天全站免登陆