[英]enable_if on member template function of class template
這接縫是MSVC10中的一個錯誤?
#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 :: type A :: t(void)”。
以下編譯:
#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>();
}
這似乎是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,那么模板似乎很愉快地編譯。
我不完全確定為什么會發生這種情況,但您可以通過使用const 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是不明確的。 希望這里的解決方法有助於通過谷歌絆倒這個...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.