当我将操作符重载为模板时会发生什么?

What happens when I overload an operator as a template?

本文关键字:什么 操作符 重载      更新时间:2023-10-16

我正在写一些笔记,为了便于编译,我为ostream添加了一个operator<<重载函数作为template。它编译得很好,但是,由于我在template<>中重载了class type操作符,并将该类型作为重载函数的第二个输入,它不会为我从现在开始定义的每个类使用新的操作符吗?这是我的代码供参考。这纯粹是为了笔记的目的,它没有任何功能。

template <class type>
ostream& operator<< (ostream& s, type x){
  s << x.getsmth();
  //...
}

当涉及到SFINAE时,我自己是一个新手,但似乎你是正确的,这个模板将用于不提供getsmth()的类,即使主体不编译。你可以用SFINAE来防止这种情况的发生,这似乎像预期的那样工作:

template <class T, typename = decltype(T().getSomething())>
std::ostream& operator<< (std::ostream& s, T& x){
  s << x.getSomething();
  return s;
}

演示:http://cpp.sh/8fyk