2012-07-02 25 views
1

我想知道是否可以部分專門化模板方法行爲,以防模板參數之一是某種類型。只專注於模板函數的一部分實現

template<class T> 
void Foo(T& parameter) 
{ 
    /* some generic - all types - stuff */ 

    If(T is int) // this is pseudo-code, typeinfo? Boost? 
    { 
     /* some specific int processing which might not compile with other types */ 
    } 

    /* again some common stuff */ 
} 

任何建議是值得歡迎的。 感謝

+0

我已經編輯因爲「部分專業化」這個術語的含義與這裏所要求的完全不同。 – bames53

回答

3

如果你只想專注功能的一部分,那麼你只需要分解出專門的實現功能的一部分:

template<class T> 
void Bar(T &t) {} 

void Bar(int &i) { 
    /* some specific int processing which might not compile with other types */ 
} 


template<class T> 
void Foo(T &t) { 
    /* some generic - all types - stuff */ 

    Bar(t); 

    /* again some common stuff */ 
} 
0

是的,你可以提供模板函數的特(只是不部分特)。對於成員函數,需要在包含模板的類後面的命名空間級別定義特化。

如果你的意思是隻有部分功能應該是專門的,你不能直接做到這一點,但你可以創建另一個模板化功能,實現邏輯的這一部分,專門化它,並從你的模板調用它。編譯器將使用Foo模板的單一版本和FooImplDetail函數的相應版本。

2

肯定的:

// helper funciton 
template <class T> 
void my_helper_function(T& v) 
{ 
    // nothing specific 
} 

void my_helper_function(int& v) 
{ 
    // int-specific operations 
} 

// generic version 
template <class T> 
void Foo(T& v) 
{ 
    /* some generic - all types - stuff */ 

    my_helper_function(v); 

    /* again some common stuff */ 
} 
+1

重載比專用更好嗎? – Flexo

+0

柔版是正確的。爲什麼專精?如果你只是提供一個'int'超載,它就會更清晰。 – mfontanini

+0

絕對正確。 – Gigi