【问题标题】:Converting std::array of std::string to std::tuple of the same size using boost::lexical_cast使用 boost::lexical_cast 将 std::string 的 std::array 转换为相同大小的 std::tuple
【发布时间】:2015-07-20 11:37:26
【问题描述】:

我想创建一个函数,它接受字符串数组并通过对每个数组元素执行 lexical_cast 将其转换为元组。

std::array 大小与 std::tuple 大小相同,所有元组类型在编译时都是已知的

例如:

std::tuple<int, double> Result = Convert({"1", "1.0"});

int A, B;
std::tie(A, B) = Convert({"1", "2"});

如何在没有 c++14 支持的情况下以可接受的性能做到这一点?

【问题讨论】:

  • 问题是什么?你已经指定了你想怎么做。实现必要的流操作。另外,我看不到问题中的 std::array

标签: c++ templates c++11 boost


【解决方案1】:

你可以这样做

namespace detail
{

    template <typename ... Ts, std::size_t N, std::size_t...Is>
    std::tuple<Ts...>
    Convert(const std::array<std::string, N>& s,
            std::index_sequence<Is...>)
    {
        return std::tuple<Ts...>{boost::lexical_cast<Ts>(s[Is])...};
    }

}

template <typename ... Ts, std::size_t N>
std::tuple<Ts...> Convert(const std::array<std::string, N>& s)
{
    static_assert(N == sizeof...(Ts), "Unexpected size");
    return detail::Convert<Ts...>(s, std::index_sequence_for<Ts...>());
}

有用法:

std::array<std::string, 2u> ns = {"1", "4.2"};
auto t = Convert<int, double>(ns);

Demo

【讨论】:

    【解决方案2】:

    您必须提供要转换成的类型。如:

    std::tuple<int, double> Result = Convert<int, double>({"1", "1.0"});
    

    这样,还不错:

    template <typename... Ts>
    std::tuple<Ts...> Convert(const std::array<std::string, sizeof... (Ts)>& arr ) {
        return Convert<Ts...>(arr, make_index_sequence<sizeof...(Ts)>{} );
    }
    
    template <typename... Ts, typename... Is>
    std::tuple<Ts...> Convert(const std::array<std::string, sizeof... (Ts)>& arr, index_sequence<Is...> ) {
        return std::make_tuple(boost::lexical_cast<Ts>(arr[Is])...));
    } 
    

    在 SO 上有几个索引序列技巧的 C++11 实现。

    【讨论】:

      猜你喜欢
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多