使用嵌套类的奇怪的enable_if行为(MSVC编译器错误或功能?)

时间:2010-07-09 00:42:03

标签: c++ visual-studio templates nested-class enable-if

经过一段时间调试我的代码后,我使用enable_if跟踪了我的问题产生一些意外的模板特化结果的原因:

以下代码在Visual Studio 2010(和2008)中的DoTest()中断言失败,而在g ++ 3.4.5中则没有。 但是,当我从 SomeClass 中移除模板或将 my_condition 移出 SomeClass 的范围时,它也适用于MSVC。

此代码是否有问题可以解释此行为(至少部分)或者这是MSVC编译器中的错误?

(使用此示例代码,它对于boost和c ++ 0x stl版本是相同的)

#include <cassert>
#include <boost\utility\enable_if.hpp>

template <class X>
class SomeClass {
public:
    template <class T>
    struct my_condition {
        static const bool value = true;
    };

    template <class T, class Enable = void> 
    struct enable_if_tester { 
        bool operator()() { return false; }
    };

    template <class T>
    struct enable_if_tester<T, typename boost::enable_if< my_condition<T> >::type> { 
        bool operator()() { return true; }
    };

    template <class T>
    void DoTest() {
        enable_if_tester<T> test;
        assert( test() );
    }
};

int main() {
    SomeClass<float>().DoTest<int>();
    return 0;
}

当尝试通过将条件移出作用域来修复它时,我也注意到使用std :: enable_if时这甚至不够,但至少它适用于boost :: enable_if:

#include <cassert>
//#include <boost\utility\enable_if.hpp>
#include <type_traits>

template <class T, class X>
struct my_condition {
    static const bool value = true;
};

template <class X>
class SomeClass {
public:
    template <class T, class Enable = void> 
    struct enable_if_tester { 
        bool operator()() { return false; }
    };

    template <class T>
    //struct enable_if_tester<T, typename boost::enable_if< my_condition<T, X> >::type> { 
    struct enable_if_tester<T, typename std::enable_if< my_condition<T, X>::value >::type> { 
        bool operator()() { return true; }
    };

    template <class T>
    void DoTest() {
        enable_if_tester<T> test;
        assert( test() );
    }
};

int main() {
    SomeClass<float>().DoTest<int>();
    return 0;
}

我希望有人对此有解释。

1 个答案:

答案 0 :(得分:4)

你的代码一切都很好,只是VC是错误的。众所周知,模板成员类的部分模板特化存在问题。