函数,该函数具有转换为字符串的可变数量的参数

function with variable number of arguments that are converted to a string

本文关键字:函数 参数 转换 字符串      更新时间:2023-10-16

我感兴趣的是创建一个C++函数,该函数接受可变数量的参数,其中每个参数可以是任意类型(我只知道使用std::to_string((将每个参数值转换为字符串是有效的(,并创建一个将所有参数值连接在单个字符串中的字符串。如何在C++11中实现这一点?我已经找到了一些在类型是先验已知的情况下进行转换的方法(例如,见下文(,但我不清楚如果类型不是先验已知的,如何进行转换。

void simple_printf(const char* fmt...)
{
va_list args;
va_start(args, fmt);
while (*fmt != '') {
if (*fmt == 'd') {
int i = va_arg(args, int);
std::cout << i << 'n';
} else if (*fmt == 'c') {
// note automatic conversion to integral type
int c = va_arg(args, int);
std::cout << static_cast<char>(c) << 'n';
} else if (*fmt == 'f') {
double d = va_arg(args, double);
std::cout << d << 'n';
}
++fmt;
}
va_end(args);
}

如果它只是级联,并且只是为std::to_string定义的类型,

#include <iostream>
#include <array>
#include <numeric>
#include <string>
template <typename...Ts>
std::string make_string(const Ts&... args)
{
std::array<std::string,sizeof...(args)> values{ std::to_string(args)...};
return std::accumulate(values.begin(),values.end(),std::string{});
}
int main() {
std::cout << make_string(1,2.0d,3.0f) << std::endl;
return 0;
}

演示