什麼是 SFINAE
SFINAE 代表 S ubstitution F ailure I s N ot A n E rror。通過替換型別(或值)來例項化函式模板或類别範本而產生的錯誤程式碼不是硬編譯錯誤,它僅被視為演繹失敗。
例項化函式模板或類别範本特化時的扣除失敗會從考慮因素中刪除該候選者 - 就好像該失敗的候選者不存在一樣。
template <class T>
auto begin(T& c) -> decltype(c.begin()) { return c.begin(); }
template <class T, size_t N>
T* begin(T (&arr)[N]) { return arr; }
int vals[10];
begin(vals); // OK. The first function template substitution fails because
// vals.begin() is ill-formed. This is not an error! That function
// is just removed from consideration as a viable overload candidate,
// leaving us with the array overload.
只有直接上下文中的替換失敗才被視為演繹失敗,所有其他失敗都被視為硬錯誤。
template <class T>
void add_one(T& val) { val += 1; }
int i = 4;
add_one(i); // ok
std::string msg = "Hello";
add_one(msg); // error. msg += 1 is ill-formed for std::string, but this
// failure is NOT in the immediate context of substituting T