有没有办法将元组转换为另一个具有不同项目类型的元组?

时间:2016-02-19 14:08:14

标签: c++11 stdtuple

是否可以将元组内的所有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在完成打印之前不会超出范围。

1 个答案:

答案 0 :(得分:2)

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

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))...
        );
}
相关问题