2012-09-09 51 views
1

是否所有的方法聲明中已模板參數需要與參數聲明一個類?編譯器似乎想要像下面C++的方法模板參數的定義

// Queue.h 
template <class ItemType> 
class Queue 
{ 
    Queue(); 
    ItemType dequeue(); 
    int count(); 
    /* ... other methods ... */ 
}; 
// Queue.cpp 
template <class ItemType> 
Queue<ItemType>::Queue() 
{ /*...*/ } 
template <class ItemType> 
int Queue<ItemType>::count() 
{/*...*/} 
template <class ItemType> 
ItemType Queue<ItemType>::dequeue() 
{/* ... */} 

從Java/C#的到來,這似乎有點多餘了 - 我覺得我應該能夠更多這樣定義方法:

int Queue::count() 

簽名不引用ItemType,所以我們可以忽略它。

Queue::ItemType Queue::dequeue() 

簽名引用的ItemType,但是編譯器知道我們正在談論的模板參數,因爲我們晉級的標識符與Queue::

+0

從技術上說,你是不是問* *的聲明,但關於*定義*的成員,在類模板聲明。 –

回答

5

是的,你需要提供模板參數。請注意,雖然它看起來多餘,但它不是。 C++模板是Java泛型的一個更強大的工具,它們允許專業化。這意味着,在基本模板Queue有可能是匹配不同的模板參數和有不同的定義是多種實現。或者,對於某些功能,您可以爲單個Queue模板提供多種專業化功能。這兩種情況下,要求您提供既template參數列表的類模板參數:

// Just member specialization 
template <typename T> 
struct X { 
    void foo() { std::cout << "generic\n"; } 
}; 
// specialize just this member for `int` 
template <> 
void X<int>::foo() { std::cout << "int\n"; } 
int main() { 
    X<double> xd; xd.foo(); // generic 
    X<int> xi; xi.foo(); // int 
} 

// Class template specialization 
template <typename T> 
struct X { 
    void foo(); 
} 
template <typename T> 
struct X<T*> { 
    void bar(); 
} 
template <typename T> 
void X<T>::foo() { std::cout << "generic\n"; } 
template <typename T> 
void X<T*>::bar() { std::cout << "ptr\n"; } 
int main() { 
    X<int > xi; xi.foo();  // generic 
    X<int*> xp; xp.bar();  // ptr 
} 
2

是的,他們這樣做,因爲Queue是不是不是多餘沒有模板參數的類型。但是,您可以提供的功能定義類模板聲明內:

template <class ItemType> 
class Queue 
{ 
    Queue(); 
    ItemType dequeue() { /* implementation */} 
    int count() { /* implementation */ } 
    /* ... other methods ... */ 
}; 

記住,這

Queue<int> q; 
int i = q.dequeue(); 

相當於

Queue<int> q; 
int i = Queue<int>::dequeue(&q); 
換句話說

,全需要類型來限定函數名,即使函數本身不引用模板參數(雖然在這種情況下,需要返回類型的模板參數)。

+0

如果沒有這個就沒有必要專門化(的例子就是Java):在語言的語法可以使用模板的名稱來引用實例化後得到的類型,在它的定義範圍內以同樣的方式一個類模板。 –

1

是。

當在類模板定義之外定義成員函數,成員類,成員枚舉,靜態數據成員或類模板的成員模板時,成員定義爲 ,定義爲模板定義其中模板參數是類模板的參數。在該構件的定義中使用的模板的參數的 名稱可能是從類模板定義中使用的模板 參數名稱不同。