Passing std::vector items to variadic function

前端 未结 5 1749
天涯浪人
天涯浪人 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:38

    Your reflexion is not at the right level of abstraction.

    When you say you want to convert the vector to a variable arguments lists, it is because the function that takes the variable argument list does something of interest to you.

    The real question is therefore, how could I do the same thing than f, but starting from a vector ?

    It is possible than forwarding the call to f might end up begin the solution, but it is not obvious.

    If it is just about printing:

    void f(std::vector const& vi) {
       bool first = true;
       for (int i: vi) {
         if (first) { first = false; } else { std::cout << ' '; }
         std::cout << i;
       }
    }
    

    Or, if you have access to outside libraries:

    #include 
    
    void f(std::vector const& vi) {
      std::cout << boost::join(vi, " ");
    }
    

    At which point the interest of f is not really evident any longer.

提交回复
热议问题