运算符<<() 失败时回退到 to_string()

Fallback to to_string() when operator<<() fails

本文关键字:lt to string 失败 运算符 回退      更新时间:2023-10-16

我见过具有相应to_string()函数的类型,但没有重载operator<<()。因此,在插入流时,必须<< to_string(x)冗长。我想知道是否可以编写一个通用函数,如果支持,用户operator<<(),如果没有,则回退到<< to_string()

SFINAE 是矫枉过正的,请使用 ADL。

诀窍是确保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;

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

尝试

template <typename T>
void print_out(T t) {
    print_out_impl(std::cout, t, 0);
}
template <typename OS, typename T>
void print_out_impl(OS& o, T t, 
                    typename std::decay<decltype(
                      std::declval<OS&>() << std::declval<T>()
                    )>::type*) {
    o << t;
}
template <typename OS, typename T>
void print_out_impl(OS& o, T t, ...) {
    o << t.to_string();
}

是的,这是可能的。

#include <iostream>
#include <sstream>
#include <string>
#include <type_traits>
struct streamy
{
};
std::ostream&
operator<<(std::ostream& os, const streamy& obj)
{
  return os << "streamy [" << static_cast<const void *>(&obj) << "]";
}
struct stringy
{
};
std::string
to_string(const stringy& obj)
{
  auto oss = std::ostringstream {};
  oss << "stringy [" << static_cast<const void *>(&obj) << "]";
  return oss.str();
}
template <typename T>
std::enable_if_t
<
  std::is_same
  <
    std::string,
    decltype(to_string(std::declval<const T&>()))
  >::value,
  std::ostream
>&
operator<<(std::ostream& os, const T& obj)
{
  return os << to_string(obj);
}
int
main()
{
  std::cout << streamy {} << 'n';
  std::cout << stringy {} << 'n';
}

仅当表达式 to_string(obj) 类型正确以obj const T&并且具有 std::string 类型的结果时,泛型operator<<才可用。正如您在评论中已经猜想的那样,这确实是 SFINAE 在起作用。如果decltype表达式格式不正确,我们将得到替换失败,重载将消失。

但是,这可能会让您遇到模棱两可的重载。至少,将回退operator<<放入其自己的namespace中,并且仅在需要时通过using声明将其拖入本地。我认为你最好写一个做同样事情的命名函数。

namespace detail
{
  enum class out_methods { directly, to_string, member_str, not_at_all };
  template <out_methods> struct tag {};
  template <typename T>
  void
  out(std::ostream& os, const T& arg, const tag<out_methods::directly>)
  {
    os << arg;
  }
  template <typename T>
  void
  out(std::ostream& os, const T& arg, const tag<out_methods::to_string>)
  {
    os << to_string(arg);
  }
  template <typename T>
  void
  out(std::ostream& os, const T& arg, const tag<out_methods::member_str>)
  {
    os << arg.str();
  }
  template <typename T>
  void
  out(std::ostream&, const T&, const tag<out_methods::not_at_all>)
  {
    // This function will never be called but we provide it anyway such that
    // we get better error messages.
    throw std::logic_error {};
  }
  template <typename T, typename = void>
  struct can_directly : std::false_type {};
  template <typename T>
  struct can_directly
  <
    T,
    decltype((void) (std::declval<std::ostream&>() << std::declval<const T&>()))
  > : std::true_type {};
  template <typename T, typename = void>
  struct can_to_string : std::false_type {};
  template <typename T>
  struct can_to_string
  <
    T,
    decltype((void) (std::declval<std::ostream&>() << to_string(std::declval<const T&>())))
  > : std::true_type {};
  template <typename T, typename = void>
  struct can_member_str : std::false_type {};
  template <typename T>
  struct can_member_str
  <
    T,
    decltype((void) (std::declval<std::ostream&>() << std::declval<const T&>().str()))
  > : std::true_type {};
  template <typename T>
  constexpr out_methods
  decide_how() noexcept
  {
    if (can_directly<T>::value)
      return out_methods::directly;
    else if (can_to_string<T>::value)
      return out_methods::to_string;
    else if (can_member_str<T>::value)
      return out_methods::member_str;
    else
      return out_methods::not_at_all;
  }
  template <typename T>
  void
  out(std::ostream& os, const T& arg)
  {
    constexpr auto how = decide_how<T>();
    static_assert(how != out_methods::not_at_all, "cannot format type");
    out(os, arg, tag<how> {});
  }
}
template <typename... Ts>
void
out(std::ostream& os, const Ts&... args)
{
  const int dummy[] = {0, ((void) detail::out(os, args), 0)...};
  (void) dummy;
}

然后像这样使用它。

int
main()
{
  std::ostringstream nl {"n"};  // has `str` member
  out(std::cout, streamy {}, nl, stringy {}, 'n');
}

函数decide_how使您可以完全灵活地决定如何输出给定类型,即使有多个选项可用。它也很容易扩展。例如,某些类型具有 str 成员函数,而不是 ADL 可查找to_string自由函数。(实际上,我已经这样做了。

该函数detail::out使用标记调度来选择适当的输出方法。

can_HOW谓词是使用我认为非常优雅的void_t技巧实现的。

可变参数out函数使用"对于每个参数"技巧,我觉得这更优雅。

请注意,代码为 C++14,需要最新的编译器。

根据@MSalters的答案(功劳归他),这个解决了我的问题,应该会做出一个完整的答案。

#include <iostream>
#include <string>
#include <type_traits>
struct foo_t {};
std::string to_string(foo_t) {
  return "foo_t";
}
template <class CharT, class Traits, class T>
typename std::enable_if<std::is_same<CharT, char>::value,
                        std::basic_ostream<CharT, Traits>&>::type 
operator<<(std::basic_ostream<CharT, Traits>& os, const T& x) {
  return os << to_string(x);
}
int main() {
  std::cout << std::string{"123"} << std::endl;
  std::cout << foo_t{} << std::endl;
}