Passing std::vector items to variadic function

前端 未结 5 1708
天涯浪人
天涯浪人 2021-01-17 17:26

I\'m using gcc 4.6. Assume that there is a vector v of parameters I have to pass to a variadic function f(const char* format, ...).

One approach of doing this is:

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 17:59

    There's a "Creating a fake va_list" section at http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html. It's for Cocoa, but you might be able to find something on the net for GCC.

    Then, I'm guessing you'd do something like this:

    #include 
    #include 
    #include 
    #include 
    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& 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 x({1, 2, 3, 4, 5});
        test(x);
    }
    

    But, I have absolutely no clue. :)

提交回复
热议问题