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

Is there a way to convert tuple to another tuple with different item type?

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

如果我们只是 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))...
        );
}