簡體   English   中英

如何使用模板模板參數專門化模板類的成員

[英]How to specialize member of template class with template template parameter

我有一個帶有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建議的解決方法,專門針對整個類,因為它只有一個成員函數和一個數據成員。

您不能部分專門化單個成員函數,您必須為整個類執行此操作。

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

由於這是不允許的,這里有一個解決方法:

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<N>())將解析為第二個函數(特化),因為我們傳遞的是int2type<1>類型的實例。 否則,將解決第一個,一般的功能。

在C ++中,不允許對函數進行部分特化; 你只能部分地專門化類和結構。 我相信這也適用於會員職能。

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

它非常小,並且有很好的代碼示例。 它將解釋patial模板函數專業化的問題,並展示其他方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM