当我将操作符重载为模板时会发生什么?
What happens when I overload an operator as a template?
我正在写一些笔记,为了便于编译,我为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
相关文章:
- c++中从整数到字符串的转换中,左移操作符是做什么的?
- 对象文件中的ostream操作符发生了什么?
- 为特定类重写new和delete操作符的原因是什么?
- 这里的虚操作符()()的目的是什么?
- c++中的操作符T* (T是模板形参)是什么?
- 赋值操作符的返回类型是什么?
- 重载操作符,本例中重载操作符的目的是什么?
- c++操作符重载中返回引用和不返回引用的区别是什么?
- new操作符返回什么?
- 标准库中自赋值不安全的move赋值操作符的基本原理是什么?
- 朋友操作符的代码示例?c++头文件,朋友在这里做什么
- c++中的定位new操作符是什么,java中有吗?
- alignof操作符的用途是什么?
- 操作符在Qt中做什么?
- 如果在调用时没有取赋值操作符的返回类型,将会发生什么?
- 字符串比较的小于操作符无论在什么情况下都会产生相同的结果
- const关键字在操作符定义中做什么?
- 当我将操作符重载为模板时会发生什么?
- 是什么?'操作符在c++中的意思
- 元操作符..的优先级是什么?