【问题标题】:Is there a way to convert tuple to another tuple with different item type?有没有办法将元组转换为具有不同项目类型的另一个元组?
【发布时间】:2016-02-19 14:08:14
【问题描述】:

是否可以将元组中的所有std::string 项目转换为const char*

template<typename... Ts>
std::tuple<Ts...> tup

我面临的问题是我尝试将可变参数模板打印到文件

fprintf(file, std::get<Idx>(tup)...)

tup 中的第一项是格式字符串(肯定是const char*),其余的是打印参数。 args 可能包含std::string。问题是fprintf 不接受std::string。如何将元组内的所有std::string 转换为const char* 并形成另一个元组?

tup 在完成打印之前不会超出范围。

【问题讨论】:

标签: c++11 stdtuple


【解决方案1】:

如果我们只是fprint-ing 元组,那么转换元组只是将它传递给其他东西。我们可以使用索引序列技巧来提取各个组件:

template <class... Ts>
void fprintf_tuple(FILE* file, std::tuple<Ts...> const& tuple) {
    fprintf_tuple(file, tuple, std::index_sequence_for<Ts...>{});
}

一旦我们有了单独的组件,我们只需要一个转换器:

template <class T> T const& convert_for_printing(T const& val) { return val; }
const char* convert_for_printing(std::string const& val) { return val.c_str(); }

然后在所有东西上调用它:

template <class... Ts, std::size_t... Is>
void fprintf_tuple(FILE* file, std::tuple<Ts...> const& tuple, std::index_sequence<Is...> )
{
    fprintf(file, 
        convert_for_printing(std::get<Is>(tuple))...
        );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多