2017-10-16 59 views
0
#include <iostream> 
#include <functional> 
#include <memory> 

using namespace std; 

template<typename T = int> std::enable_if_t<!std::is_arithmetic<T>{}, T> nope() {} 

int main() { 
    nope(); 
} 

這是一個簡單的代碼,不會編譯。如果一個人改變了這一點:enable_if如何在這種情況下工作

int main() { 
     nope(); 
} 

int main() { 
     nope<std::string>(); 
} 

它開始編譯。 問題是爲什麼這個工作像它的工作?更具體地講,爲什麼編譯器告訴我:

呼叫到 '沒了()'

,而不是像

enable_if沒有匹配功能::類型未找到 (這是真的,因爲如果條件不滿足,它確實不存在)?

謝謝。

+0

既然你問爲什麼編譯偏好另一個錯誤信息,你應該用你正在使用的編譯器標記這個問題。 –

+0

你看到的是[SFINAE](http://en.cppreference.com/w/cpp/language/sfinae)。 – HolyBlackCat

+0

GCC和Clang都給出了體面的錯誤消息。 Clang甚至給出了註釋:候選模板被忽略:被'enable_if'[with T = int]禁用,使用enable_if_t = typename enable_if <_Cond, _Tp> :: type;' – NathanOliver

回答

0

如果您致電nope(),您的template類型默認爲intstd::enable_if_t<!std::is_arithmetic<T>{}, T>返回false!std::is_arithmetic<int>{}並失敗。

nope<int>()的調用也會失敗,原因與爲什麼nope()失敗相同。

另一方面,nope<std::string>得到trueis_arithmetic並返回一個工作函數。

被觸發5.0 clang++版本的編譯器錯誤解釋的結果很清楚:

候選模板忽略:要求「!std::is_arithmetic<int>{}」不滿意[with T = int] std::enable_if_t<!std::is_arithmetic<T>{}, T> nope() {}

+0

是的,我明白了。但據我瞭解std :: enable_if_t <!std :: is_arithmetic {},T>不會返回false,因爲它的定義如下: template using enable_if_t = typename enable_if : :類型; 它應該不會引發編譯器錯誤,因爲類型未在B情況下定義==假? – s0nicYouth

+0

它會引發編譯器錯誤,請參閱上面的@ nwp的註釋。我的海灣合作委員會也不太清楚,但鏗鏘的信息是清楚的。 – Chiel

相關問題