在其他模板类中专门化可变参数模板类是合法的 [英] Is it legit to specialize variadic template class inside other template class

查看:146
本文介绍了在其他模板类中专门化可变参数模板类是合法的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个代码:

#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 ++中编译,但我不相信它是合法的。至于我知道一个不能例如专门为模板类的模板方法如果不明确专门化类本身。

It does compile in both g++ and clang++ but I am not convinced it is legal. As far as I know one cannot for example specialize template method for template class if not explicit specializing the class itself. How come rules are different for inner classes?

推荐答案

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

A partial specialization of a nested template class is OK:

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> {};
};

内部类的显式(完整)专业化不是。

An explicit (full) specialization of the inner class only is not.

外部类的显式特化(无需内部类的特殊化(实际上是一个不同的类))和外部和内部类的显式特化是可能的:

Explicit specializations of the outer class (without specialization of the inner class (which is actually a different class)) and explicit specializations of the outer and inner class are possible:

#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();
}

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

Note: The same applies to non variadic nested template classes.

这篇关于在其他模板类中专门化可变参数模板类是合法的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆