在类template的成员模板函数上启用le_if

enable_if on member template function of class template

本文关键字:启用 le if 函数 template 成员 在类      更新时间:2023-10-16

这似乎是MSVC10中的一个bug ?

#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型::t(空白)"。

以下编译:

#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:programmingstackoverflowstackoverflowstackoverflow.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的使用有歧义。