我正在使用列出的资源学习 C++ 模板 here 。特别是,请阅读模板参数推导。现在,阅读后,为了进一步澄清我对该主题的概念,我尝试了以下示例,该示例在 gcc 中编译,但不在 clang 和 msvc 中编译。 Demo
template<typename T = int> void f()
{
}
template<typename T> void func(T)
{
}
int main()
{
func(f); //works in gcc but not in clang and msvc
func(f<>); //works in all
}
正如我们所看到的,上面的例子在 gcc 中编译得很好,但在 clang 和 msvc 中则不行。 我的问题是根据最新标准,哪个编译器是正确的?
最佳答案
这是CWG 2608并且该程序格式良好,因此 gcc 正确接受该程序。
来自temp.arg.explicit#4这是由于 cwg 2608 添加的,可以使用默认模板参数和空模板参数列表 <>
可以省略。
If all of the template arguments can be deduced or obtained from default template-arguments, they may all be omitted; in this case, the empty template argument list <> itself may also be omitted.
(强调我的)
请注意上面引用的语句中粗体突出显示的部分,这意味着空模板参数列表 <>
在您的示例中可以省略,因为所有模板参数都可以从默认模板参数中获取。
此外,over.over#3也可以在这里使用来查看从 temp.arg.explicit 生成的特化添加到重载集中:
The specialization, if any, generated by template argument deduction ([temp.over], [temp.deduct.funcaddr], [temp.arg.explicit]) for each function template named is added to the set of selected functions considered.
(强调我的)
这意味着最后,调用 func(f);
格式良好并使用生成的特化 f<int>
.
关于c++ - 函数模板参数推导适用于 gcc,但不适用于 msvc 和 clang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73415321/