简体   繁体   English

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

[英]What happens when I overload an operator as a template?

I am writing some notes, and just for the sake of compiling, I added an operator<< overloaded function for the ostream as a template . 我正在写一些注释,只是为了编译,我为ostream添加了一个operator<<重载函数作为template It compiles just fine but, since I overloaded the operator with class type inside the <> of template and passed that type as the second input for the overloaded function, won't it use the new operator for EVERY class that I define from now on? 它编译得很好但是,因为我在template<>中重载了class type的操作符并将该类型作为重载函数的第二个输入传递,所以它不会使用new运算符来表示我从现在开始定义的每个类? Here's my code for reference. 这是我的代码供参考。 It's purely for note purposes, it has no functionality. 它纯粹是出于注意目的,它没有任何功能。

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

I'm myself a novice when it comes to SFINAE, but it seems like you are correct, this template will be used for classes which don't offer getsmth() , even though the body doesn't compile. 对于SFINAE,我本身就是一个新手,但看起来你是对的,这个模板将用于不提供getsmth() ,即使正文不能编译。 You can prevent this from happening with SFINAE though, this seems to work as expected: 你可以使用SFINAE防止这种情况发生,但这似乎按预期工作:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM