【发布时间】:2017-01-04 22:03:02
【问题描述】:
.
#include <iostream>
#include <type_traits>
using namespace std;
template<typename T>
struct MyClass{
void hello( void) {
hello(std::is_same<T,bool>());
}
void hello(std::true_type){
cout<<"hello only for bools"<<endl;
}
};
int main(int argc, char** argv){
MyClass<bool> myclass1;
myclass1.hello();
MyClass<float> myclass2;
//myclass2.hello(); //throws error as it should
return 0;
}
我在阅读enable_if method specialization后编写了上面的代码。我希望 hello() 方法仅在模板参数为 bool 且有效时才存在。但是,当我尝试使用 enable_if 解决相同的问题时,我遇到了问题。我有以下代码。任何帮助表示赞赏。如果 enable_if 不适合这个工作,一般用什么?
#include <iostream>
#include <type_traits>
using namespace std;
template<typename T>
struct MyClass{
typename std::enable_if<std::is_same<T,bool>::value, void>::type
hello(void)
{
cout<<"hello only for bools"<<endl;
}
};
int main(int argc, char** argv){
MyClass<bool> myclass1;
myclass1.hello();
MyClass<float> myclass2;// compilation error. Don't know how to solve
//myclass2.hello(); //I want only this line to cause compilation error
return 0;
}
编辑:我在 jpihl 的回答 std::enable_if to conditionally compile a member function 中找到了我的问题的解决方案。但是谁能解释一下为什么上述方法不起作用?
#include <iostream>
#include <type_traits>
using namespace std;
template<typename T>
struct MyClass{
template<class Q = T>
typename std::enable_if<std::is_same<Q, bool>::value, void>::type hello()
{
cout<<"hello only for bools"<<endl;
}
};
int main(int argc, char** argv){
MyClass<bool> myclass1;
myclass1.hello();
MyClass<float> myclass2;// throws errow. Don't know how to solve
myclass2.hello(); //
return 0;
}
【问题讨论】:
标签: template-meta-programming sfinae enable-if