gpt4 book ai didi

c++ - 将未知类型和数量的 args 和 concat 传递给 char 数组

转载 作者:行者123 更新时间:2023-11-27 23:57:59 24 4
gpt4 key购买 nike

有没有办法将未知数量的 args(可以是 char 字符串或整数)传递给函数,然后将它们连接到 char 数组缓冲区?

例如,能够调用以下所有函数:

bufcat("this", 1, 3, "that");  
// buffer = "this13that"
bufcat(1, "this", "that", 3, 4000000, "other");
// buffer = "1thisthat34000000other"
bufcat(1000000,2,3,4,5,6,7,8,9,10,11,12,13,"onemillionandfiftytwo");
// buffer = "10000002345678910111213onemillionandfiftytwo"

最佳答案

您可以使用可变模板加上字符串流:

template<typename... Args>
std::string bufcat(Args&&... args) {
std::stringstream ss;

auto iteration = [&ss](auto&& item) { ss << std::forward<decltype(item)>(item); };

(void)std::initializer_list<int> {(
iteration(std::forward<Args>(args))
, 0)..., 0};

return ss.str();
}

这会将您传入参数的任何内容连接到字符串流中。它将为 Args 中的每个参数调用 iteration lambda。

然后,您可以像这样简单地调用您的函数:

bufcat(1000000,2,3,4,5,6,7,8,9,10,11,12,13,"onemillionandfiftytwo");

它会产生 10000002345678910111213onemillionandfiftytwo

关于c++ - 将未知类型和数量的 args 和 concat 传递给 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41200713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com