就SFINAE而言,访问不存在的成员不被视为"error"吗?



我已经为漂亮的打印对实现了重载:

template<typename P>
ostream &operator<<(ostream &os, const P &p) {
  using std::operator<<;
  os << '(' << p.first << ", " << p.second << ')';
  return os;
}
但是,在它存在的情况下,

编译器很难判断它是否应该应用标准重载或我上面定义的重载,即使在选择应该很明显的情况下也是如此:

int main() {
  cout << "SFINAE sure is hard to grasp!n";
}
error: use of overloaded operator '<<' is
      ambiguous (with operand types 'std::ostream' (aka 'basic_ostream<char>') and
      'const char [30]')

我不太明白问题是什么。我尝试打印的字符数组显然没有firstsecond成员,因此使用我的重载实例化它会导致错误。

难道SFINAE不应该尝试执行替换,发现缺少成员并丢弃结果吗?如果没有,为什么?

SFINAE 在过载解析期间工作:

此规则在函数模板的重载解析期间适用:当将显式指定或推导的类型替换为模板参数失败时,将从重载集中丢弃专用化,而不是导致编译错误。

这意味着只有函数模板的签名才会对 SFINAE 生效,不会检查实现。

您可以将重载更改为

template <typename T, typename = void>
struct pairable : std::false_type {};
// check whether type T has first and second members
template <typename T>
struct pairable<T, std::void_t<decltype(std::declval<T>().first),
                               decltype(std::declval<T>().second)>>
    : std::true_type {};
// the template parameter is the part of the signature of function template
template<typename P, std::enable_if_t<pairable<P>::value>* = nullptr>
ostream &operator<<(ostream &os, const P &p) {
  using std::operator<<;
  os << '(' << p.first << ", " << p.second << ')';
  return os;
}

> SFINAE 仅适用于函数签名:即参数类型、返回类型和限定符,例如:const、非const。它不适用于函数的实现。

在您的情况下,函数签名与调用匹配。因此,该函数被实例化,并且期望编译时没有错误。

最新更新