3

这似乎是 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>();
}
4

1 回答 1

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 ints 来表示模板参数来使这段代码工作:

    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 的使用不明确。希望这里的解决方法对通过谷歌偶然发现这个问题的人有所帮助......

于 2012-11-20T16:28:25.020 回答