经过一段时间调试我的代码,我跟踪了我的问题的原因,使用enable_if:

的一些意外模板专业化结果

以下代码失败了Visual Studio 2010(和2008)中的DOTEST()中的断言,而它不在G ++ 3.4.5中。 但是,当我从 someClass 或移动 my_condition 外,在 someclass 中的范围内,它也在msvc中工作。

这个代码有问题,这些代码可以解释这种行为(至少部分),或者是msvc编译器中的错误吗?

(使用此示例代码对增强和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;
}
.

我希望有人对此进行解释。

有帮助吗?

解决方案

您的代码一切都很好,这只是VC是越野车。众所周知,模板成员类的部分模板专业有问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top