c – 当operator <<()失败时,回退到to_string()

前端之家收集整理的这篇文章主要介绍了c – 当operator <<()失败时,回退到to_string()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经看到类型具有相应的to_string()函数,但没有重载运算符<<().因此,当插入流时,必须<< to_string(x),这是详细的.我想知道是否可以编写用户操作符<<()的通用函数(如果支持)并且回退到<< to_string()如果没有.

解决方法

SFINAE过度使用,使用ADL.

诀窍是确保操作符<<是可用的,不一定是类型定义提供的那个:

  1. namespace helper {
  2. template<typename T> std::ostream& operator<<(std::ostream& os,T const& t)
  3. {
  4. return os << to_string(t);
  5. }
  6. }
  7. using helper::operator<<;
  8. std::cout << myFoo;

这个技巧通常用在通用代码中,需要在std :: swap< T>之间进行选择.和专门的Foo :: swap(Foo :: Bar&,Foo :: Bar&).

猜你在找的C&C++相关文章