工作在返回類型但不作為模板參數的SFINAE我已經用了很多次SFINAE的成語,我習慣了把我的std::enable_if<>在模板參數中,而不是在返回類型中。然而,我遇到了一些瑣碎的情況,它不起作用,我不知道為什么。首先,這是我的主要:int main(){
foo(5);
foo(3.4);}下面是foo觸發錯誤:template<typename T,
typename = typename std::enable_if<std::is_integral<T>::value>::type>auto foo(T)
-> void{
std::cout << "I'm an integer!\n";}template<typename T,
typename = typename std::enable_if<std::is_floating_point<T>::value>::type>auto foo(T)
-> void{
std::cout << "I'm a floating point number!\n";}下面是一段可以正常工作的代碼:template<typename T>auto foo(T)
-> typename std::enable_if<std::is_integral<T>::value>::type{
std::cout << "I'm an integrer!\n";}template<typename T>auto foo(T)
-> typename std::enable_if<std::is_floating_point<T>::value>::type{
std::cout << "I'm a floating point number!\n";}我的問題是:為什么第一次執行foo觸發該錯誤,而第二個錯誤不觸發?main.cpp:14:6: error: redefinition of 'template<class T, class> void foo(T)'
auto foo(T)
^main.cpp:6:6: note: 'template<class T, class> void foo(T)' previously declared here auto foo(T)
^main.cpp: In function 'int main()':main.cpp:23:12: error: no matching function for call to 'foo(double)'
foo(3.4);
^main.cpp:6:6: note: candidate: template<class T, class> void foo(T)
auto foo(T)
^main.cpp:6:6: note: template argument deduction/substitution failed:main.cpp:5:10: error: no type named 'type' in 'struct std::enable_if<false, void>'
typename = typename std::enable_if<std::is_integral<T>::value>::type>
^編輯 :工作代碼和錯誤碼.
3 回答

慕后森
TA貢獻1802條經驗 獲得超5個贊
14.5.6.1 Function template overloading

冉冉說
TA貢獻1877條經驗 獲得超1個贊
template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>auto foo(T) -> void{ std::cout << "I'm an integer!\n";}template<typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>auto foo(T) -> void{ std::cout << "I'm a floating point number!\n";}
- 3 回答
- 0 關注
- 500 瀏覽
添加回答
舉報
0/150
提交
取消