这是可编译和按预期工作的代码。 (感谢juanchopanza)
第一个版本(正确)
#include <iostream>
#include <string>
using namespace std;
enum EN{ EN1,EN2 };
template<EN T1> class B{
//#BLOCK
public: template<EN enLocal=T1> typename
std::enable_if<enLocal==EN1,void>::type test(){ //<-- not cute
std::cout<<"EN1"<<std::endl;
}
public: template<EN enLocal=T1> typename
std::enable_if<enLocal==EN2,void>::type test(){ //<-- not cute
std::cout<<"EN2"<<std::endl;
}
//#END BLOCK
};
int main() {
B<EN1> b;
b.test(); //should print "EN1"
return 0;
}
我认为代码难以阅读且不可爱。
因此,我尝试提高可读性#BLOCK
到下面的代码,但它不再可编译。
为什么? ...我认为第二个版本对我来说更容易理解。
第二版(不可编辑)
//#BLOCK
public: typename std::enable_if<T1==EN1,void>::type test(){ //<-- cute
std::cout<<"EN1"<<std::endl;
}
public: typename std::enable_if<T1==EN2,void>::type test(){ //<-- cute
//^ error: functions that differ only in their return type cannot be overloaded
std::cout<<"EN2"<<std::endl;
}
//#END BLOCK
更具体地说,哪个C ++语言规范使第二个版本无法编译?
为什么我不能将T1
放在std::enable_if<>
内?
我是C ++的新手。