gpt4 book ai didi

c++ - 使用C++-17,如何从字符串 vector 填充元组

转载 作者:行者123 更新时间:2023-12-01 14:44:01 27 4
gpt4 key购买 nike

使用C++-17,有一种惯用的方法可以将std::vector转换为std::tuple,只要存在从std::string到Args ...列表中每个Arg类型的合理转换即可。

将此破损的代码视为描述此想法的一种方式。

template<class T> T transform_arg(std::string const &s);
template<> double transform_arg(std::string const &s) { return atof(s.c_str());}
template<> int transform_arg(std::string const &s) { return atoi(s.c_str());}

template<typename... Args>
std::tuple<Args...> create_tuple(std::vector<std::string> arguments) {
return std::make_tuple<Args...>(transform_arg<Args>(arguments.pop_back()), ...));
}

假设我们以这种方式调用它。
std::vector<std::string> args;
args.push_back("3.14");
args.push_back("2");
args.push_back("1.0");
create_tuple<double,int,double>(args);

这将生成一个元组为double,int,double的元组,并通过转换函数将这些值填充到元组内部。

最佳答案

无法将std::string输入的值映射到多种类型,因为该值仅在运行时才知道。

最好的办法是从 vector 中创建一个元组,前提是您知道在编译时的大小:

template <std::size_t... Is>
auto create_tuple_impl(std::index_sequence<Is...>, const std::vector<std::string>& arguments) {
return std::make_tuple(arguments[Is]...);
}

template <std::size_t N>
auto create_tuple(const std::vector<std::string>& arguments) {
return create_tuple_impl(std::make_index_sequence<N>{}, arguments);
}

用法:
const std::vector<std::string> inputs{"100", "42.22"};
const auto t = create_tuple<2>(inputs);

live example on godbolt.org

编辑:如果要手动选择类型:
template<class T> T transform_arg(std::string const &s);
template<> double transform_arg(std::string const &s) { return atof(s.c_str());}
template<> int transform_arg(std::string const &s) { return atoi(s.c_str());}

template <typename... Args, std::size_t... Is>
auto create_tuple_impl(std::index_sequence<Is...>, const std::vector<std::string>& arguments) {
return std::make_tuple(transform_arg<Args>(arguments[Is])...);
}

template <typename... Args>
auto create_tuple(const std::vector<std::string>& arguments) {
return create_tuple_impl<Args...>(std::index_sequence_for<Args...>{}, arguments);
}

用法:
const std::vector<std::string> inputs{"100", "42.22", "11"};
const auto t = create_tuple<int, double, int>(inputs);

static_assert(std::is_same_v<decltype(t), const std::tuple<int, double, int>>);

live example on godbolt.org

关于c++ - 使用C++-17,如何从字符串 vector 填充元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59195526/

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