2010-02-20 41 views
3

我讀的STL源代碼(這竟然是既有趣又非常有用),和我碰到這種事情來爲什麼使用模板<>沒有專業化?

//file backwards/auto_ptr.h, but also found on many others. 

template<typename _Tp>                         
     class auto_ptr 

//Question is about this: 
template<> 
    class auto_ptr<void> 

是在template<>部分加入,以避免重複類?

+0

你的頭銜很混亂,你究竟是什麼意思? – GManNickG 2010-02-20 04:47:10

+0

我在問什麼模板<>是。 – Tom 2010-02-20 04:56:10

+0

這只是用來說「這是一個模板類,但我不需要任何模板」的語法,因爲你會自己填充它。 – GManNickG 2010-02-20 04:59:56

回答

7

這就是專業化。例如:

template <typename T> 
struct is_void 
{ 
    static const bool value = false; 
}; 

此模板將有is_void<T>::valuefalse任何類型,這顯然是不正確。你可以做的就是使用這個語法說:「我T中填充我自己,專業」:

template <> // I'm gonna make a type specifically 
struct is_void<void> // and that type is void 
{ 
    static const bool value = true; // and now I can change it however I want 
}; 

現在is_void<T>::value是除了當Tvoidfalse。然後編譯器選擇更專用的版本,我們得到true

因此,在你的情況下,它有一個auto_ptr的通用實現。但是這種實現在void上有問題。具體而言,它不能被解除引用,因爲它沒有與之相關的類型。

所以我們可以做的是專門0123Åvoid變種刪除這些功能。

+0

謝謝,非常好的解釋。 – Tom 2010-02-20 05:03:38