【问题标题】:Is it legit to specialize variadic template class inside other template class在其他模板类中专门化可变参数模板类是否合法
【发布时间】:2016-10-12 12:33:28
【问题描述】:

考虑一个代码:

#include <iostream>

template <class T>
struct outer {
   template <class... Args>
   struct inner {
      static constexpr bool value = false;
   };

   template <class... Other>
   struct inner<T, Other...> {
      static constexpr bool value = true;
   };
};

int main() {
   std::cout << outer<int>::inner<int, void>::value << std::endl;
};

它确实可以在 g++ 和 clang++ 中编译,但我不相信它是合法的。据我所知,如果没有明确地专门化类本身,就不能例如专门化模板类的模板方法。为什么内部类的规则不同?

【问题讨论】:

  • 您没有专门研究模板方法。您正在部分专攻一门完整的课程。

标签: c++ templates c++11 variadic-templates template-specialization


【解决方案1】:

嵌套模板类的部分特化是可以的:

template <class T>
struct outer {
    // template
   template <class... Args>
   struct inner {};

    // partial
   template <class... Other>
   struct inner<T, Other...> {};

    // error: explicit specialization in non-namespace scope ‘struct inner’
    // template <>
    // struct inner<char, int> {};
};

仅内部类的显式(完全)特化不是。

外部类的显式特化(没有内部类的特化(实际上是不同的类))以及外部和内部类的显式特化是可能的:

#include <iostream>
template <class T>
struct outer {
   template <class... Args>
   struct inner
   {
       static void print() { std::cout << "outer<T>::inner<Args...>\n"; }
   };
};

template <> // outer specialization
struct outer<int>
{
   template <class... Args>
   struct inner
   {
       static void print() { std::cout << "outer<int>::inner<Args...>\n"; }
   };
};

template <> // outer specialization
template <> // inner specialization
struct outer<int>::inner<int> // must be outside of the outer class
{
    static void print() { std::cout << "outer<int>::inner<int>\n"; }
};

int main() {
    outer<char>::inner<char>::print();
    outer<int>::inner<char>::print();
    outer<int>::inner<int>::print();
}

注意:同样适用于非可变嵌套模板类。

【讨论】:

  • 这可以解释为什么不能专门化方法,因为它确实需要完全专门化。但是规则背后的原因对我来说不是很清楚......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多