c++ - 在 temp.deduct.partial 中,为什么参数包不够专业?

标签 c++ templates c++17

temp.deduct.partial#8 ,有一个例子:

template<class... Args>           void f(Args... args);         // #1
template<class T1, class... Args> void f(T1 a1, Args... args);  // #2
template<class T1, class T2>      void f(T1 a1, T2 a2);         // #3

f();                // calls #1
f(1, 2, 3);         // calls #2
f(1, 2);            // calls #3; non-variadic template #3 is more specialized
                    // than the variadic templates #1 and #2

第 1 次调用很简单,因为只有一个可行的特化。

对于调用 #2,f₁f₂ 是可行的。我们合成了 f₁(X)f₂(X, Y)。然后我们以两种方式进行类型推导。

首先 f₂(X, Y)f₁(Args... args),推导出 ArgsX , Y

然后 f₁(X) 对抗 void f₂(T1 a1, Args... args),将 T1 推导为 XArgs 为空。

所以演绎在两种方式上都成功,而且没有一种比另一种更专业。

我们能被temp.deduct.partial#11拯救吗? ?

If, after considering the above, function template F is at least as specialized as function template G and vice-versa, and if G has a trailing parameter pack for which F does not have a corresponding parameter, and if F does not have a trailing parameter pack, then F is more specialized than G.

这看起来没有帮助。设 F=f₁, G=f₂,则 G 确实有一个 F 没有相应参数的尾随参数包。但是 F 有一个尾随参数包,所以这不适用。

我是否误读了标准中的任何内容,或者答案是否完全可以在其他地方找到?

最佳答案

这是 answered由西蒙·布兰德在推特上发布。关键在temp.deduct#type-10.2 :

During partial ordering, if Ai was originally a function parameter pack: (...) if Pi is not a function parameter pack, template argument deduction fails.

在这种情况下,当针对 f₂(T1 a1, Args... args) 执行 f₁(X) 时,X 最初是一个函数参数包。 T1 不是函数参数包,因此推导失败。

由于我们可以从 f₂ 推导出 f₁,但反之则不行,因此 f₂ 更专业。

关于c++ - 在 temp.deduct.partial 中,为什么参数包不够专业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54980350/

相关文章:

c++ - 为什么 C+ +'s ` 变量模板的行为不符合预期?

java - 以编程方式从内置摄像头捕获视频

c++ - C++ 成员函数中的 "if (!this)"有多糟糕?

C++ 实现我自己的 static_assert

c++ - 是否可以在可变参数模板函数中扩展非可变参数?

c++ - C++17和C++11中的非类型模板参数有什么区别?

c++ - 具有 invoke_result 的重载命名非成员函数的返回类型

c++ - QTableView如何获取滚动条所在行的位置

c++ - 使用 sse 和 avx 内在函数将一组打包的单打添加到一个值中

c++ - 使用 const 限定符将参数传递给模板函数时出错