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

Lin*_*gxi 6 c++ overloading tostring template-meta-programming c++11

我见过具有相应to_string()功能的类型,但没有超载operator<<().因此,在插入流时,必须使用<< to_string(x)详细信息.我想知道是否有可能编写一个通用函数,operator<<()如果支持用户,<< to_string()如果没有,则回退.

MSa*_*ers 9

SFINAE过度使用,使用ADL.

诀窍是确保a operator<<可用,不一定是类型定义提供的:

namespace helper {
   template<typename T> std::ostream& operator<<(std::ostream& os, T const& t)
   {
      return os << to_string(t);
   }
}
using helper::operator<<;
std::cout << myFoo;
Run Code Online (Sandbox Code Playgroud)

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