mfy*_*fya 5 c++ templates nested-class visual-studio 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;
}
Run Code Online (Sandbox Code Playgroud)
当试图通过将条件移出范围来修复它时,我还注意到使用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;
}
Run Code Online (Sandbox Code Playgroud)
我希望有人对此有所解释。