这只是一个关于风格的问题:我不喜欢 C++ 的模板元编程方式,它要求您使用返回类型或为 SFINAE 的技巧添加一个额外的虚拟参数。所以,我想出的想法是将 SFINAE 东西放在模板参数定义本身中,如下所示:
#include <iostream>
#include <boost/type_traits/is_array.hpp>
#include <boost/utility/enable_if.hpp>
using namespace std;
template <typename T, typename B=typename boost::enable_if< boost::is_array<T> >::type > void asd(){
cout<<"This is for arrays"<<endl;
}
template <typename T, typename B=typename boost::disable_if< boost::is_array<T> >::type > void asd(){
cout<<"This is for NON arrays"<<endl;
}
int main() {
asd<int>();
asd<int[]>();
}
这个例子让 g++ 抱怨:
../src/afg.cpp:10:97: 错误: 'template void asd()' 的重新定义</p>
SFINAE 本身可以工作,因为如果我删除例如带有disable_if
的那个,编译器错误是:
../src/afg.cpp:15:12: 错误:没有匹配函数调用'asd()'</p>
这就是我想要的。
那么,有没有办法在函数的“正常”签名中完成 SFINAE,即返回类型 + 参数列表?
编辑:这最终是我要在真实代码中尝试的:
#include <iostream>
#include <type_traits>
using namespace std;
template <typename T, typename enable_if< is_array<T>::value, int >::type =0 > void asd(){
cout<<"This is for arrays"<<endl;
}
template <typename T, typename enable_if< !is_array<T>::value, int >::type =0 > void asd(){
cout<<"This is for NON arrays"<<endl;
}
int main() {
asd<int[]>();
asd<int>();
}
我使用 c++0x 的东西而不是 boost,因为只要我需要 c++0x 来使用模板参数的默认值,我认为没有理由使用 boost,它是它的前身。