c++ - 类模板的成员模板函数上的enable_if

标签 c++ visual-studio templates typetraits enable-if

这似乎是 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 的使用不明确。希望这里的解决方法对通过谷歌遇到这个问题的人有帮助......

关于c++ - 类模板的成员模板函数上的enable_if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8538171/

相关文章:

c# - 如何公开 C# "using"别名以避免 "inconsistent accessibility"错误?

android - Visual Studio Cordova Gradle 构建失败

c++ - 可变参数模板中的总和类型

c++ - 提供适当的 operator<< 和可变模板特化

c++ - MySQL C API : Segmentation Fault when running query from different thread

c++ - 编译时的派生类发现

visual-studio - 在 Visual Studio 中升级 Azure Functions 项目

c++ - 衍生出奇怪的重复模板和协方差

C++ 和 Qt : Paint Program - Rendering Transparent Lines Without Alpha Joint Overlap

c++ - 实践中的 Pimpl 成语