2011-12-16 114 views
3

此接縫是MSVC10中的一個錯誤?enable_if類模板的成員模板函數

#include <type_traits> 

template<int j> 
struct A{ 
    template<int i> 
    typename std::enable_if<i==j>::type 
     t(){} 
}; 

int main(){ 
    A<1>().t<1>(); //error C2770 
} 

錯誤C2770:無效明確template_or_generic參數(一個或多個) 「enable_if ::類型A ::噸(無效)」。

下編譯:

#include <type_traits> 

template<class j> 
struct A{ 
    template<class i> 
    typename std::enable_if<std::is_same<i,j>::value>::type 
     t(){} 
}; 

template<unsigned int j> 
struct B{ 
    template<unsigned int i> 
    typename std::enable_if<i==j>::type 
     t(){} 
}; 

int main(){ 
    A<int>().t<int>(); 
    B<1>().t<1>(); 
} 
+1

在g ++和鏗鏘++的作品。你有#include `和`使用std :: enable_if`嗎? – kennytm 2011-12-16 17:57:26

回答

1

這似乎是MSVC2010的部分地方是無法作出判斷,以一些奇怪的行爲是否你的< 1>作爲模板參數是一個使用實例化基於int的模板。

當我編譯上面的代碼,我得到以下,詳細的錯誤:

error C2770: invalid explicit template argument(s) for 
    'std::enable_if<i==1>::type A<j>::t(void)' 
    with 
    [ 
     j=1 
    ] 
    d:\programming\stackoverflow\stackoverflow\stackoverflow.cpp(11) : 
    see declaration of 'A<j>::t' 
    with 
    [ 
     j=1 
    ] 

如果你交換你的1個值超出了0,你會發現它仍然無法正常工作,但如果你使用任何其他有效的int,模板看起來很高興編譯。

我不完全知道爲什麼發生這種情況,但你可以通過使用常量整數來表示模板參數使此代碼的工作:

template<int j> 
    struct A{ 
     template<int i> 
     typename std::enable_if<i == j>::type 
      t(){} 
    }; 

    int main(){ 

     const int j = 1; 
     const int i = 1; 

     A<j>().t<i>(); //now compiles fine 
    } 

我懷疑,在此基礎上,是編譯器發現在模板實例化時使用0和1不明確。希望這裏的解決方法有助於有人通過谷歌絆倒這...