【问题标题】:How to specialize member of template class with template template parameter如何使用模板模板参数专门化模板类的成员
【发布时间】:2011-09-26 17:33:48
【问题描述】:

我有一个带有 int 和模板模板参数的模板类。 现在我想专门化一个成员函数:

template <int I> class Default{};
template <int N = 0, template<int> class T = Default> struct Class
{
    void member();
};

// member definition
template <int N, template<int> class T> inline void Class<N, T>::member() {}

// partial specialisation, yields compiler error
template <template<int> class T> inline void Class<1, T>::member() {}

谁能告诉我这是否可行以及我在最后一行做错了什么?

编辑:我要感谢大家的意见。由于我还需要对某些 ​​T 进行专门化,因此我选择了 Nawaz 建议的解决方法并专门化了整个类,因为无论如何它只有一个成员函数和一个数据成员。

【问题讨论】:

    标签: c++ templates template-specialization


    【解决方案1】:

    你不能部分特化单个成员函数,你必须为整个类做。

    template <int I> class Default{};
    template <int N = 0, template<int> class T = Default> struct Class
    {
        void member();
    };
    
    // member definition
    template <int N, template<int> class T> inline void Class<N, T>::member() {}
    
    // partial specialization
    template <template<int> class T> struct Class<1, T>
    {
      void member() {}
    };
    

    【讨论】:

      【解决方案2】:

      由于这是不允许的,这里有一种解决方法:

      template <int I> class Default{};
      
      template <int N = 0, template<int> class T = Default> 
      struct Class
      {
          void member()
          {
               worker(int2type<N>()); //forward the call
          }
       private:
           template<int N> struct int2type {};
      
           template<int M>
           void worker(const int2type<M>&) //function template
           {
               //general for all N, where N != 1
           }
           void worker(const int2type<1>&) //overload 
           {
               //specialization for N == 1
           }
      };
      

      这个想法是,当 N=1 时,函数调用 worker(int2type&lt;N&gt;()) 将解析为第二个函数(特化),因为我们传递了 int2type&lt;1&gt; 类型的实例。否则,将解析第一个通用函数。

      【讨论】:

        【解决方案3】:

        在 C++ 中,不允许对函数进行部分特化;您只能部分专门化类和结构。我相信这也适用于成员函数。

        【讨论】:

          【解决方案4】:

          查看这篇文章:http://www.gotw.ca/publications/mill17.htm

          它很小,并且有很好的代码示例。它将解释空间模板函数专业化的问题,并展示解决它的其他方法。

          【讨论】:

            猜你喜欢
            • 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
            相关资源
            最近更新 更多