2011-09-27 69 views
1

我一直在搞enable_if,我似乎已經偶然發現了一些不一致的行爲。這是在VS2010中。我已將它縮減爲以下示例。std :: enable_if專業化失敗

#include <type_traits> 

using namespace std; 

// enable_if in initial template definition 
template <class T, class Enable = enable_if<true>> struct foo {}; 

foo<int> a; //OK 

// explicit specialisation 
template <class T, class Enable = void> struct bar; 
template <class T> struct bar<T, void> {}; 

bar<int> b; //OK 

// enable_if based specialisation 
template <class T, class Enable = void> struct baz; 
template <class T> struct baz<T, std::enable_if<true>> {}; 

baz<int> c; //error C2079: 'c' uses undefined struct 'baz<T>' 

這是代碼或編譯器中的錯誤嗎?

回答

3

您的問題已經很少做enable_if

// you declare a structure named baz which takes 2 template parameters, with void 
// as the default value of the second one. 
template <class T, class Enable = void> struct baz; 
// Partial specialization for a baz with T and an std::enable_if<true> 
template <class T> struct baz<T, std::enable_if<true>> {}; 

// Declare a baz<int, void> (remember the default parameter?): 
baz<int> c; //error C2079: 'c' uses undefined struct 'baz<T>' 

baz<int, void>有在這一點上不完全類型。會出現同樣的問題,而enable_if

template <class T, class U = void> 
struct S; 

template <class T> 
struct S<T, int> 
{ }; 

S<double> s; 

而且,正如詹姆斯說,你正在使用enable_if不正確。 Boost's documentation for enable_if做了很好的解釋。

6

std::enable_if<true>應該是typename std::enable_if<true>::type

std::enable_if<true>總是命名一個類型(如std::enable_if<false>)。爲了在條件爲false時讓替換失敗,您需要使用嵌套的typedef,它只在條件爲真時才被定義。

+0

啊當然。謝謝! – Ayjay

+0

@McNellis:「爲了在條件爲false時獲得替換失敗,您需要使用類型嵌套的typedef,它只在條件爲真時才被定義」......這是否有意義?這意味着你永遠無法讓替代失敗。那是你的意思嗎? –