函数,该函数具有转换为字符串的可变数量的参数
function with variable number of arguments that are converted to a string
我感兴趣的是创建一个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;
}
演示
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数