其他分享
首页 > 其他分享> > c – SFINAE是否依赖于类型扣除?

c – SFINAE是否依赖于类型扣除?

作者:互联网

我对cppreference.com中的以下引用感到困惑:

This rule applies during overload resolution of function templates: When substituting the deduced type for the template parameter fails, the specialization is discarded from the overload set instead of causing a compile error.

这是否意味着SFINAE无法在没有类型扣除的情况下工作?例如,请考虑以下代码:

template <typename T> std::true_type has_value_type_helper(typename T::value_type*);
template <typename> std::false_type has_value_type_helper(...);

template <typename T> inline constexpr bool has_value_type_v
   = decltype(has_value_type_helper<T>(nullptr))::value;

int main() {
   std::cout << has_value_type_v<int> << std::endl;
   std::cout << has_value_type_v<std::vector<int>> << std::endl;
}

它按预期工作,但据我所知,没有类型扣除.模板参数在has_value_type_helper< T>(nullptr)中明确提供.甚至SFINAE可以用这种方式吗?

解决方法:

Can even SFINAE be used this way?

是.

替换是扣除过程的一部分.明确提供模板参数并不能消除替换的需要([temp.deduct]/2) – 而且它是替换(SFINAE中的S)失败并非错误([temp.deduct]/8).

在这种情况下,当您向has_value_type_helper显式提供T时,我们仍然需要将T替换为参数T :: value_type.这是在替换的直接上下文中,因此如果该替换失败 – 对于类似int的类型而言,它没有名为value_type的嵌套类型别名 – 它是……而不是错误,我们只是从考虑中移除候选者.我们有另一个备用候选者,所以这很好.

标签:type-deduction,template-deduction,c,sfinae
来源: https://codeday.me/bug/20190724/1521147.html