2015-05-31 58 views
1

函數(或部分)的編制提供類如防止基於模板參數

template<typename T = void> 
class Foo 
{ 
    void Baz() 
    { 
     // Do something regardless of specialization 
     /* Do stuff if the template was specified (i.e. if not void) */ 
     /* This cannot be handled with an if statement because it will not compile if T == void */  
    } 

    /* Rest if class */ 
} 

我怎樣才能讓編譯器知道,它不應該編譯如果T == void功能的一個部分?我最初試着用if這個陳述來做這件事,但是它不會編譯,因爲那段代碼使用<<運算符和一個T類型的變量(如果T == void顯然是錯誤的)。

回答

2

您不能使用類模板參數來獲取SFINAE成員函數。

您可以使用成員函數模板參數像以下:

template<typename T = void> 
class Foo 
{ 
    public: 
    template <typename Dummy = char> 
    void Baz(typename std::enable_if< !std::is_same<T ,void>::value, 
           Dummy>::type * = 0) 
    { 
     // ... 
    } 
}; 

See Here

+0

謝謝:)我只是意識到我傳遞了函數'Baz'兩個參數(都是'unsigned int')。我如何在您提供的示例中包含這些內容?我試圖只是看到,如果把它們放在參數列表的開始/結尾工作,但我錯了 – Kvothe

1

使用模板特這樣的:

#include <iostream> 

template<class T> 
void BazHelper(){ 
    // Do something regardless of specialization 
    /* Do stuff if the template was specified (i.e. if not void) */ 
    std::cout << "Not void code\n"; 
} 

template <> 
void BazHelper<void>(){ 
    // Do something regardless of specialization 
    /* Do NOT do stuff if the template was specified (i.e. if not void) */ 
    std::cout << "void code\n"; 
} 

template<typename T = void> 
struct Foo{ 
    void Baz() 
    { 
     // Do something regardless of specialization 
     BazHelper<T>(); 
     /* Do stuff if the template was specified (i.e. if not void) */ 
     /* This cannot be handled with an if statement because it will not compile if T == void */ 
    } 

    /* Rest if class */ 
}; 

int main(){ 
    Foo<> vf; 
    vf.Baz(); 
    Foo<double> df; 
    df.Baz(); 
} 
+0

謝謝,我已決定採用現在給出的另一種方法,但我會記住這一點 – Kvothe