gpt4 book ai didi

c++ - 将 std::vector 项传递给可变参数函数

转载 作者:可可西里 更新时间:2023-11-01 17:46:57 37 4
gpt4 key购买 nike

我正在使用 gcc 4.6。假设有一个参数 vector v​​ 我必须传递给可变参数函数 f(const char* format, ...)。

这样做的一种方法是:

        void VectorToVarArgs(vector<int> &v)
{
switch(v.size())
{
case 1: f("%i", v[0]);
case 2: f("%i %i", v[0], v[1]);
case 3: f("%i %i %i", v[0], v[1], v[2]);
case 4: f("%i %i %i %i", v[0], v[1], v[2], v[3]);

// etc...
default:
break;
}
}

// where function f is
void f(const char* format, ...)
{
va_list args;
va_start (args, format);
vprintf (format, args);
va_end (args);
}

问题当然是它不支持 vector v 中的任意数量的项目。但是,我相信已经理解 va_lists 原则上是如何工作的,即通过从堆栈中读取参数,从“...”之前的最后一个命名参数的地址开始,现在我认为应该可以将 vector 项值复制到内存块(例如 myMemBlock)并将其地址作为“格式”之后的第二个参数传递。显然,这需要 myMemBlock 的结构符合 f() 的预期,即像堆栈一样。

  1. 这样的事情可行吗?
  2. 或者,是否可以使用一些内联汇编程序魔术将 vector 项值推送到实际堆栈上,调用函数 f() 然后清理堆栈?

最后,我不关心的事情:

  1. 代码可能不可移植。好的,我只是对 gcc 感兴趣。
  2. 可能还有其他涉及预处理器黑客的方法。
  3. C++ 不鼓励像 printf() 这样使用可变参数函数进行格式化。
  4. 可变模板函数的使用。

最佳答案

http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html 有一个“创建假的 va_list”部分.它适用于 Cocoa,但您可以在网上找到适用于 GCC 的内容。

那么,我猜测你会做这样的事情:

#include <string>
#include <cstdio>
#include <vector>
#include <cstdarg>
using namespace std;

struct my_list {
unsigned int gp_offset;
unsigned int fp_offset;
void *overflow_arg_area;
void *reg_save_area;
};

void f(const char* format, ...) {
va_list args;
va_start (args, format);
vprintf (format, args);
va_end (args);
}

void test(const vector<int>& v) {
string fs;
for (auto i = v.cbegin(); i !=v.cend(); ++i) {
if (i != v.cbegin()) {
fs += ' ';
}
fs += "%i";
}
my_list x[1];
// initialize the element in the list in the proper way
// (however you do that for GCC)
// where you add the contents of each element in the vector
// to the list's memory
f(fs.c_str(), x);
// Clean up my_list
}

int main() {
const vector<int> x({1, 2, 3, 4, 5});
test(x);
}

但是,我完全没有头绪。 :)

关于c++ - 将 std::vector<int> 项传递给可变参数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9276902/

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