2011-08-19 162 views
2

這是很容易的,我堅持要弄清楚如何實際使用,模板專業化需要

template<class C> 
struct P{ 
}; 

template<> 
struct P<int>{}; 

是否有這樣的特定專業化實際的應用?

+2

沒有任何上下文,有點難以分辨。 –

+0

就像你想說的那樣,他們*實際* *都是空的? –

+0

由於其他原因,這實際上並不是一件好事,它實際上是在STL內部完成的,'std :: vector '是'std :: vector <>'模板的一個特例 –

回答

5

雖然您的具體示例看起來不太有趣,但模板專業化被廣泛使用。下面是一個例子:

template< class T > 
struct StringConverter 
{ 
    static std::string Convert(const T&) 
    { 
    //do some conversion from T to string using stringstream for instance 
    //and return result 
    } 
} 

template<> 
struct StringConverter<std::string> 
{ 
    static std::string Convert(const std::string& t) 
    { 
    //no need for conversion here! 
    return t; 
    } 
} 

//usage: 
std::string a = StringConverter<int>::Convert(5); //default impl 
std::string b = StringConverter<std::string>::Convert("b"); //specialized 
+2

我讀了_wildly_而不是_widely_ 。看起來更合適;-) – rodrigo

+0

@rodrigo aha不錯的一個 – stijn