Why can#39;t the compiler deduce the template type from default arguments?(为什么编译器不能从默认参数推导出模板类型?)
问题描述
我很惊讶下面的代码会导致 无法推导出 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
修复了这个问题.为什么编译器不能从默认参数中推导出类型?
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):
非推导的上下文是:
...
- 在函数形参的形参类型中使用的模板形参,该形参有一个默认实参,该实参在正在执行自变量推导的调用中使用.
这篇关于为什么编译器不能从默认参数推导出模板类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么编译器不能从默认参数推导出模板类型?


基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01