C++ 将 std::tuple<char, char, char> 转换为 std::string?

标签 c++ c++17 template-meta-programming stdtuple conversion-operator

我正在编写一个轻量级解析器组合库(类似于 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/

相关文章:

c++ - 调试断言失败的 Opencv 函数

c++ - Sun Studio 链接 gcc 库 : exceptions do not work

c++ - 针对编译时常量优化的函数

c++ - clang 和 gcc 为相同的代码生成不同的逻辑。哪个是对的?

c++ - 默认模板参数中的 MPL 占位符替换

c++ - 使用不包括基类的模板从 C++ 列表中查找特定类型

c++ - 在 QT 中,从 closeEvent 函数发出信号是否安全?

c++ - 而无限循环?

c++ - 如果我将可变 lambda 作为 const 引用传递给函数,会发生什么情况?

c++ - 尝试禁用无参数成员函数时,SFINAE 无法在 decltype() 内工作