【问题标题】:partial class template specialization with parameter pack not in last position参数包不在最后位置的部分类模板特化
【发布时间】:2016-10-06 02:51:13
【问题描述】:

以下代码来自an answer to another question,它可以工作。我用最新版本的 GCC、Clang、ICC 和 MSVC 对其进行了测试。但是我不明白标准的哪一部分允许这种构造,请您帮忙?

template<class F, class Alloc> class C; //undefined
template<class T, class... Args, class Alloc>
class C<T(Args...), Alloc> {
    // implementation
};

C++ 标准对如何在主类模板中使用参数包提供了限制,但我无法弄清楚这些限制如何应用于部分特化。

所以我的问题是:在 C++ 标准中定义的部分模板专业化的上下文中,参数包的放置规则在哪里?

【问题讨论】:

  • 您的实际问题是什么?部分专业化如何运作?
  • 你的意思是像here
  • 谢谢,这看起来确实是正确的主题。但是它说“如果一个参数是一个包扩展([temp.variadic]),它应该是模板参数列表中的最后一个参数。”这似乎与示例相矛盾,还是我遗漏了什么?
  • @Drealmer T(Args...) 不是包扩展参数。 Args... 将是一个包扩展参数
  • 好的,这开始有意义了,谢谢大家!但是这是否说明了参数包在专业化参数列表中的放置? (因为关于参数列表的部分确实没有问题)

标签: c++ variadic-templates


【解决方案1】:

虽然不是理解部分专业化如何工作的正式且技术上正确的方法(请查看 the cppreference page 以获得更多技术解释),您可以考虑您发布的代码 sn-p 术语“模式匹配”的(就像一个直觉

// `C` is a template class that takes two types as template parameters.
template<class F, class Alloc> class C; 

// I'm going to specialize `C` so that:
// * The first type will be a function signature type, where the return
//   type is going to be matched by `T` and the argument types will be 
//   matched by `Args...`.
// * The second type will be an user-provided `Alloc` typename.
template<class T, class... Args, class Alloc>
class C<T(Args...), Alloc> { /* ... */ };

假设我像这样实例化C

using My_C = C<int(float, char), std::allocator<int>>;
My_C c;

非常粗略地说,My_C“匹配”C&lt;T(Args...), Alloc&gt; 部分模板特化如下:

int ( float, char )     std::allocator<int>
^^^   ^^^^^^^^^^^       ^^^^^^^^^^^^^^^^^^^
 T  (    Args...  )           Alloc
^^^^^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^^^^^
         F                    Alloc

intT“匹配”float, charArgs...“匹配”。没有理由将Args... 限制为C 的最后一个模板参数。

如您所见,Args... 参数包不需要作为最后一个模板参数,因为我们只是使用它为传递的函数签名中的参数类型列表“提供名称”。

【讨论】:

  • 介意解释否决票吗?我将问题解释为“我认为参数包需要位于参数列表的末尾,但我不明白为什么这段代码有效”,并试图对角色进行非正式解释Args... 在发布的代码 sn-p 中。
  • 我也不理解反对票,这不是我的。
  • 我们在 C++ 中并没有真正的“模式匹配”。选择偏特化涉及模板推导和偏序。
  • @Barry:我知道这一点,我使用“模式匹配”一词来提供一种直觉,以便轻松理解Args... 在 sn-p 中的作用。我会在回答中更清楚地说明“模式匹配”不是在技术层面上发生的。
猜你喜欢
  • 2013-09-11
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多