c++11 how to implement `std::string ToString(std::

2019-04-14 12:09发布

问题:

I want a very friendly ToString function for many types, include the std::tuple. The function is like this:

template <typename T>
inline std::string ToString(const T &t) { 
    std::stringstream ss;
    ss << t;
    return ss.str();
}

template <typename... Args>
inline std::string ToString(const std::tuple<Args...> &t) {
    std::stringstream ss;
    for (int i = 0; i < t.size(); i++) {
        ss << ToString(std::get<i>(t)) << " ";
    }
    return ss.str();
}

The second part is wrong on grammar, how to implement it with c++11 template ?

And, how to implement the FromString like this:

template <typename T>
inline T FromString(const std::string &s) {
    std::stringstream ss(s);
    T t;
    ss >> t;
    return t;
}

template <typname... Args>
inline std::tuple<Args...> FromString(const std::string &s) {
    std::tuple<Args...> ret;
    ret.resize(sizeof...Args);
    std::stringstream ss;
    size_t pos;
    for (int i = 0, prev_pos = 0; i < sizeof...Args and prev_pos < s.length(); i++) {
        pos = s.find(" ", prev_pos);
        T t = FromString(s.substr(prev_pos, pos));
        std::get<i>(ret) = t;
        prev_pos = pos
    }
    return ret;
}

The second part is also wrong on c++11 grammar, how to implement it ?

回答1:

In C++17, you may do:

template <typename ... Ts>
std::string ToString(const Ts& ... ts) { 
    std::stringstream ss;
    const char* sep = "";
    ((static_cast<void>(ss << sep << ts), sep = " "), ...);
    return ss.str();
}

template <typename... Args>
std::string ToString(const std::tuple<Args...> &t) {
    return std::apply([](const auto&... ts) { return ToString(ts...); }, t);
}

Demo



回答2:

namespace notstd {
  template<std::size_t...Is>
  struct index_sequence {};
  template<std::size_t N, std::size_t...Is>
  struct make_index_sequence:make_index_sequence<N-1,N-1,Is...>{};
  template<std::size_t...Is>
  struct make_index_sequence<0,Is...>:index_sequence<Is...>{};

#define RETURNS(...) \
  noexcept(noexcept(__VA_ARGS__)) \
  -> decltype(__VA_ARGS__) \
  { return __VA_ARGS__; }

  namespace details {
    template<class F, class Tuple, std::size_t...Is>
    auto apply( F&& f, Tuple&& tuple, index_sequence<Is...> )
    RETURNS( std::forward<F>(f)( std::get<Is>(std::forward<Tuple>(tuple))... ) )
    template<class Tuple>
    using raw_tuple = typename std::remove_cv<typename std::remove_reference<Tuple>::type>::type;
    template<class Tuple>
    using tuple_count = std::tuple_size< raw_tuple<Tuple> >;
  }
  template<class F, class Tuple>
  auto apply( F&& f, Tuple&& tuple )
  RETURNS(
    ::notstd::details::apply(
      std::forward<F>(f),
      std::forward<Tuple>(tuple),
      ::notstd::make_index_sequence<
        ::notstd::details::tuple_count<Tuple>::value
      >{}
    )
  )
}

now this ::notstd::apply behaves a lot like C++17's std::apply.

We then glue this to your ToString via ToStream:

struct to_stream_t;

template<class...Args>
void ToStream(std::ostream& os, const std::tuple<Args...>& t) {
  os << '{';
  ::notstd::apply( to_stream_t{os}, t );
  os << '}';
}
inline void ToStream(std::ostream&) {}
template<class T>
void ToStream(std::ostream& os, const T& t) { 
  os << t;
}
template<class T0, class... Ts>
void ToStream(std::ostream& os, const T0& t0, const Ts& ... ts) { 
  ToStream(os, t0);
  using discard=int[];
  (void)discard{0,((
    void(os << ' '), to_stream_t{os}(ts)
  ),0)...};
}
struct to_stream_t {
  std::ostream& os;
  template<class...Args>
  void operator()(Args const&...args) const {
    ToStream(os, args...);
  }
};
template<class...Ts>
std::string ToString( Ts const&... ts ) {
  std::stringstream ss;
  ToStream( ss, ts... );
  return ss.str();
}

this also flattens recursive tuples.

If you add more std or fundamental type manual ToStream implementations, put them before the body of to_stream_t or recursion won't work. And recurse via to_stream_t{os}(t) instead of ToStream(os, t) generally so you find the right overloads.

Test code:

std::tuple<std::string, std::string, int> t("hello", "world", 42);
std::cout << ToString(t, "-", t);

Live example.

We can augment with vector support:

template<class T, class A>
void ToStream(std::ostream& os, const std::vector<T, A>& v) {
  os << '[';
  for (auto const& x:v)
  {
    if (std::addressof(x) != v.data())
        os << ',';
    to_stream_t{os}(x);
  }
  os << ']';
}

then test with all of this:

std::tuple<std::string, std::string, int> t("hello", "world", 42);
std::cout << ToString(t, "-", t) << "\n";
std::vector< int > v {1,2,3};
std::cout << ToString(v) << "\n";
std::vector< std::tuple<int, int> > v2 {{1,2},{3,4}};
std::cout << ToString(v2) << "\n";
auto t2 = std::tie( v, v2 );
std::cout << ToString(t2) << "\n";

Live example.

The end output is:

{hello world 42} - {hello world 42}
[1,2,3]
[{1 2},{3 4}]
{[1,2,3] [{1 2},{3 4}]}

as expected.



回答3:

In C++11 you may want to give up do this

#include<iostream>
#include<tuple>
#include<utility>
#include<sstream>

template<size_t... I>
struct index_sequence {};

template<size_t N, size_t sz, size_t... I>
struct make_index_sequence_
{
    using type = typename make_index_sequence_<N, sz + 1, I..., sz>::type;
};

template<size_t N, size_t... I>
struct make_index_sequence_<N, N, I...>
{
    using type = index_sequence<I...>;  
};

template<size_t N>
using make_index_sequence = typename make_index_sequence_<N, 0>::type;

template<typename Fn, typename Tuple, size_t... I>
auto apply_(Fn&& fn, Tuple&& tup, index_sequence<I...>) -> decltype(fn(std::get<I>(tup)...))
{
    return fn(std::get<I>(tup)...);
}

template<typename Fn, typename Tuple>
auto apply(Fn&& fn, Tuple&& tup) -> decltype(apply_(std::forward<Fn>(fn), std::forward<Tuple>(tup), make_index_sequence<std::tuple_size<typename std::remove_reference<Tuple>::type>::value>{}))
{
    return apply_(std::forward<Fn>(fn), std::forward<Tuple>(tup), make_index_sequence<std::tuple_size<typename std::remove_reference<Tuple>::type>::value>{});
}

All those above is re-implementing the standard library in newer C++.

template<typename T>
std::string ToString(const T& t)
{ 
    std::stringstream ss;
    ss << t;
    return ss.str();
}

template<typename T, typename... Ts>
std::string ToString(const T& t, const Ts&... ts)
{
    return ToString(t) + ToString(ts...);   
}

template<typename... Ts>
std::string ToString(const std::tuple<Ts...>& tup)
{
    return apply<std::string (*)(const Ts&...)>(ToString, tup);   
}

And these are the real logic.

Live

Gave me appreciation on a whole new level just how great syntax sugar is.