简体   繁体   English

C++ 转一个 std::tuple<char, char, char> 进入 std::string?</char,>

[英]C++ turn a std::tuple<char, char, char> into a std::string?

I am writing a lightweight parser combinator library (akin to Boost::Spirit) as hobby project.我正在编写一个轻量级解析器组合库(类似于 Boost::Spirit)作为爱好项目。

One thing I'd like to do, is to automatically be able to convert a Result<std::tuple<char>> , Result<std::tuple<char, char>> , etc. into a std::string .我想做的一件事是能够自动将Result<std::tuple<char>>Result<std::tuple<char, char>>等转换为std::string

And similarly, if having eg a Result<std::tuple<int, int>> I'd like to be able to convert it to a Result<std::vector<int>> or more generally for any tuple containing zero or more elements of the same type T I'd like to be able to convert it automatically to a Result<Container<T>> .同样,如果有例如Result<std::tuple<int, int>>我希望能够将其转换为Result<std::vector<int>>或更一般地用于包含零或的任何元组更多相同类型的元素T我希望能够将其自动转换为Result<Container<T>>

How does one tackle something like this?如何处理这样的事情? I attempted for instance:例如,我尝试过:

  template<typename Container>
  Result<decltype(std::make_from_tuple<Container>(std::declval<T>()))> () const {
      Result{Container{std::make_from_tuple<std::initializer_list<typename std::tuple_element<0, T>::type>> (std::get<T>(*this))}};
  }

but this does not work, as it turns out that it's not possible to create an initializer list programmatically like this.但这不起作用,因为事实证明不可能像这样以编程方式创建初始化列表。

template <typename... Ts>
std::string tuple_to_string(const std::tuple<Ts...>& t)
{
    return std::apply([](auto... cs)
    { 
        return std::string{cs...}; 
    }, t);
}

live example on godbolt.org godbolt.org 上的实时示例


More generic solution:更通用的解决方案:

template <typename T, typename... Ts>
T tuple_to_container(const std::tuple<Ts...>& t)
{
    return std::apply([](auto... cs){ return T{cs...}; }, t);
}

Usage:用法:

std::tuple test0{'a', 'b', 'c'};
std::tuple test1{'a', 'b', 'c', 'd', 'e', 'f'};

std::cout << tuple_to_container<std::string>(test0) << '\n'
          << tuple_to_container<std::string>(test1) << '\n';

std::tuple test2{0, 1, 2, 3};
auto converted = tuple_to_container<std::vector<int>>(test2);
assert(converted == (std::vector{0, 1, 2, 3}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM