c++ - 如何将可变长度参数作为字符串连接
问题描述
我想在函数中传递变长参数,用逗号连接这些参数,最后返回带括号的字符串形式。如果参数类型是字符串或者char *,那么自动加上单引号,这是怎么回事呢?谢谢!例如:join(1, 2, "hello", 3, "world") 返回字符串 "(1, 2, \"hello\", 3, \"world\")"
解决方案
您可以创建一些功能模板来完成这项工作。
#include <iostream>
#include <sstream>
#include <type_traits>
// a function that takes a variable amount of arguments
template<typename T, class... Args >
std::string join_helper(const T& t, Args...args) {
std::ostringstream ss;
using type = std::remove_cv_t<std::remove_reference_t<T>>;
// check if " should be added
if constexpr(std::is_same_v<type, const char*> ||
std::is_same_v<type, std::string> ||
std::is_same_v<type, std::string_view>)
{
ss << '"';
}
ss << t; // stream out the current value
if constexpr(std::is_same_v<type, const char*> ||
std::is_same_v<type, std::string> ||
std::is_same_v<type, std::string_view>)
{
ss << '"';
}
// do we have more arguments? if so, add ", " and call join_helper again
if constexpr (sizeof...(args) > 0) {
ss << ", ";
ss << join_helper(args...);
}
return ss.str();
}
// the function you will use that adds ( and ) around the return value from join_helper
template<class... Args>
std::string join(Args...args) {
if constexpr(sizeof...(args) > 0)
return '(' + join_helper(args...) + ')';
else
return "()";
}
int main() {
std::cout
<< join(1, 2.3, "hello", 4, std::string("world")) << '\n'
<< join() << '\n'
;
}
输出:
(1, 2.3, "hello", 4, "world")
()
推荐阅读
- ruby-on-rails - 安装 Poppler Gem 并在运行服务器时出现捆绑程序错误
- android - Socket.emit 不适用于向上和返回按钮_Android
- eslint - 将 ESLint 配置为在使用某些键定义对象时出错
- javascript - (CORS) - 跨域资源共享连接问题
- tensorflow - TensorFlow 数据管道
- python - 图像处理 - 如何将图像列表及其标签存储在单热编码的 ndarray 中?
- i3 - i3:从不同工作区的游侠启动 mpv
- http - 什么时候可以在 GET http 请求的请求行上有相对 URL?
- c# - 如何将列表写入文本文件。每行写 50 个项目
- python - 组合列表以获取项目组的最有效方法 <= 但尽可能接近长度 X