c ++ 11如何实现`std :: string ToString(std :: tuple <args ...>&amp; t)`?

时间:2017-07-13 13:27:57

标签: c++ c++11 templates stdtuple

我想要一个非常友好的a.b_childern.append(b)函数用于许多类型,包括ToString。功能是这样的:

std::tuple

第二部分语法错误,如何用c ++ 11模板实现?

并且,如何实现这样的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(); }

FromString

关于c ++ 11语法的第二部分也是错误的,如何实现呢?

3 个答案:

答案 0 :(得分:7)

在C ++ 17中,您可以这样做:

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

答案 1 :(得分:4)

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
      >{}
    )
  )
}

现在这个::notstd::apply的行为很像C ++ 17 std::apply

然后我们通过ToString

将其粘贴到您的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();
}

这也会使递归元组变平。

如果您添加了更多std或基本类型的手动ToStream实施,请将放在 to_stream_t的主体之前,否则递归工作将无法完成。并且通过to_stream_t{os}(t)代替ToStream(os, t)进行递归,以便找到正确的重载。

测试代码:

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

Live example

我们可以通过矢量支持来增强:

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 << ']';
}

然后测试所有这些:

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

结束输出是:

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

正如所料。

答案 2 :(得分:1)

在C ++ 11中,你可以想要放弃这样做

#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>{});
}

以上所有内容都是在较新的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);   
}

这些都是真正的逻辑。

Live

让我欣赏一个全新的水平,即语法糖的优秀程度。