【问题标题】:enable_if on member template function of class templateenable_if 对类模板的成员模板函数
【发布时间】:2012-01-22 05:11:20
【问题描述】:

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

【问题讨论】:

  • 在 g++ 和 clang++ 中工作。你有#include &lt;type_traits&gt;using std::enable_if吗?
  • 错误是什么?不要发布“不工作”。 “不工作”是什么意思?是没有编译,还是什么?
  • 奇怪的是,如果您将两个模板参数的类型都更改为unsigned int,甚至long,MSVC10 似乎很高兴。这可能是您可以接受的解决方案。
  • 没有名为&lt;typetraits&gt; 的标头。应该是&lt;type_traits&gt;
  • 它适用于charboolsize_tlong,它适用于不等于0或1的int! (好吧,我检查了2)。有关相关问题,请参阅 stackoverflow.com/questions/2763836/…

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


【解决方案1】:

这似乎是 MSVC2010 的一些奇怪行为,它无法确定您使用 作为模板参数是否是基于 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 的使用不明确。希望这里的解决方法对通过 google 偶然发现此问题的人有所帮助...

【讨论】:

    猜你喜欢
    • 2012-10-01
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 2014-02-11
    • 2021-12-26
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多