2011-01-21 61 views
4

如何對類GList進行部分特化,以便可以存儲I的指針(即I *)?針對指針的部分特化,C++

template <class I> 
struct TIList 
{ 
    typedef std::vector <I> Type; 
}; 


template <class I> 
class GList 
{ 
     private: 
      typename TIList <I>::Type objects; 
}; 

回答

7

您不需要專門化就可以做到這一點。它可以存儲指針。

GList<int*> ints; 

無論如何,如果你想專門化指針GList,使用以下語法。

template <class I> 
class GList<I*> 
{ 
    ... 
}; 

就用I,你會在任何正常的模板。在上面的示例GList<int*>中,將使用指針專用化,並且I將是int

+0

和專業類爲Glist 必須自己實現的私有數據成員的對象? – Woody 2011-01-22 14:03:06

+0

是的,專業化與原始基礎模板不分享任何內容。你必須重新編寫所有的成員變量和成員函數(或者如果可能的話,將它們分解成一個公共基類)。 – 2011-01-22 14:40:49

5

上一篇文章指出,您不需要專門針對指針類型,但可以。

考慮以下幾點:

struct Bar { 
    void bar(void) { /* do work */ } 
}; 

template <class T> struct Foo { 
    T t; 

    void foo(void) 
    { 
     t.bar(); // If T is a pointer, we should have used operator -> right? 
    } 
}; 

int main(int argc, char * argv[]) 
{ 
    Foo<Bar *> t; 

    t.foo(); 
} 

這不會編譯。因爲在Foo :: foo中我們有一個指針,我們用它作爲變量。

如果您添加以下,它將使用專業化和精細編譯:

// This is a pointer to T specialization! 
template <class T> class Foo<T *> { 
    T * t; 
public: 
    void foo(void) 
    { 
     t->bar(); 
    } 
};