为什么编译器不能从默认参数中推导出模板类型? [英] Why can't the compiler deduce the template type from default arguments?

查看:199
本文介绍了为什么编译器不能从默认参数中推导出模板类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶以下代码导致无法推导出T 错误的模板参数:

I was surprised the following code resulted in a could not deduce template argument for T error:

struct foo
{
  template <typename T>
  void bar(int a, T b = 0.0f)
  {
  }
};

int main()
{
  foo a;
  a.bar(5);

  return 0;
}

调用 a.bar< float& 修正了问题。为什么编译器不能从默认参数推导出类型?

Calling a.bar<float>(5) fixes the issue. Why can't the compiler deduce the type from the default argument?

推荐答案

在C ++ 03中,规范明确禁止默认参数用于推导模板参数(C ++ 03§14.8.2/ 17):

In C++03, the specification explicitly prohibits the default argument from being used to deduce a template argument (C++03 §14.8.2/17):


类型参数不能从函数默认参数的类型中推导出来。

A template type-parameter cannot be deduced from the type of a function default argument.

在C ++ 11中,您可以为函数模板提供一个默认模板参数:

In C++11, you can provide a default template argument for the function template:

template <typename T = float>
void bar(int a, T b = 0.0f) { }

参数是必需的,但。如果未提供默认模板参数,则默认函数参数仍然不能用于模板参数推导。具体来说,以下适用(C ++ 11 14.8.2.5/5):

The default template argument is required, though. If the default template argument is not provided, the default function argument is still not usable for template argument deduction. Specifically, the following applies (C++11 14.8.2.5/5):


未推导出的上下文是:

The non-deduced contexts are:

...


  • 在参数类型中使用的模板参数,

这篇关于为什么编译器不能从默认参数中推导出模板类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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