簡體   English   中英

模板專業化與模板類

[英]Template specialization with template class

我做了以下事情。

template <class C> class B{};

template <class X> 
struct  A{
  int member;
};

template <class Y> 
struct  A<B<Y>>{
    A(int n):member(n){}
};

int main(int, char**){}

即類X可能是模板本身,對於這種情況,我想要專門化A類模板。
但編譯說:

d:\>g++ -std=gnu++11 -o spec.exe spec.cpp
spec.cpp: In constructor 'A<B<Y> >::A(int)':
spec.cpp:11:14: error: class 'A<B<Y> >' does not have any field named 'member'  

如果A<B<Y>>類完全與A分開,那么一切都是正確的,並且可能沒有A任何成員。 但我想要A專業化。 全部內容。
或者,可能是,當XB<Y>時, A一些專門構造函數。
如何實施?

模板特化是一種與繼承完全不同的機制。 它不擴展通用模板的內容:它用專門案例的新內容替換它們。 所以編譯器是對的:你的類A<B<Y>>沒有任何名為member字段。 它只有一個構造函數,它接受一個int和一些額外的自動生成的函數(復制構造函數,析構函數等)。

如果要“繼承”模板的內容,您有兩種選擇:

  • 將模板中的所有內容復制到專門化中
  • 將公共內容放在基類中並從中繼承

根據您的要求,其中一個選項將優於另一個選項。

這是如何實現它:

template <class C> class B{};

template <class X>
struct  A{
  int member;
};

template <class Y>
struct  A<B<Y> >{ // A<
    int member;  // just add member here
    A(int n):member(n){}
};

當你實現模板特化時,就像你正在定義一個全新的類。

我想你要找的是成員函數專門化,但是這個不支持部分特化,如果你試圖專門化給定模板類的構造函數,那么必須隱式聲明這個構造函數。

template <class C> class B{};

template <class X>
struct  A{
  A(int n); // I implicitly-declared the constructor that I want to specialize. 
            // you can still define it if you want.
  int member;
};
// this is the contructor specialization,
// Note this isn't partial specialization, it's explicit specialization so you
// must provide a type that you want to specialize it with, in this case B<int>
template <>
A<B<int> >::A(int n):member(n){}

暫無
暫無

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

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