問題描述
我很驚訝下面的代碼會導致 無法推導出 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):
非推導的上下文是:
...
- 在函數形參的形參類型中使用的模板形參,該形參有一個默認實參,該實參在正在執行自變量推導的調用中使用.
這篇關于為什么編譯器不能從默認參數推導出模板類型?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!