gpt4 book ai didi

C++ 将 std::tuple 转换为 std::string?

转载 作者:行者123 更新时间:2023-12-04 00:51:00 24 4
gpt4 key购买 nike

我正在编写一个轻量级解析器组合库(类似于 Boost::Spirit)作为业余项目。
我想做的一件事是自动能够转换 Result<std::tuple<char>> , Result<std::tuple<char, char>>等变成std::string .
同样,如果有例如Result<std::tuple<int, int>>我希望能够将其转换为 Result<std::vector<int>>或更一般地,对于包含零个或多个相同类型元素的任何元组T我希望能够将其自动转换为 Result<Container<T>> .
一个人如何处理这样的事情?我尝试例如:

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

但这不起作用,因为事实证明不可能像这样以编程方式创建初始化列表。

最佳答案

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

更通用的解决方案:
template <typename T, typename... Ts>
T tuple_to_container(const std::tuple<Ts...>& t)
{
return std::apply([](auto... cs){ return T{cs...}; }, t);
}
用法:
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}));

关于C++ 将 std::tuple<char, char, char> 转换为 std::string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66663472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com