hardyz009
hardyz009

Reputation: 149

How to retrieve the entire va_list input

I am familiar with va_arg list. I wanted to know is there a way through which we could fetch the value after comma

Eg

abc("%d %d %d how are you",1,2,3);

i want to know if it is possible to pass this entire call to a string without any processing like

string [1]="%d %d %d how are you",1,2,3;

I dont want to do any kind of processing , i simply want to read the entire call and store it in a string of array.

Upvotes: 1

Views: 217

Answers (3)

M.M
M.M

Reputation: 141638

Since C++17 you can capture all the arguments and forward them to a stringstream in a single expression (called a fold-expression):

#include <string>
#include <sstream>
#include <iostream>
#include <functional>

std::string abc(auto&& head, auto&&... tail)
{
    std::ostringstream out;
    out << head;
    ((out << ',' << tail), ...);

    return out.str();
}

int main()
{
    std::string s = abc("%d %d %d how are you", 1, 2, 3);

    std::cout << s << std::endl;
}

Prior to C++17, but since C++11, you could use a recursive template (or the void braced list hack which I won't go into here). Snippet:

template<typename Head>
void capture(std::ostream& out, Head&& head)
{
    out << std::forward<Head>(head);
}

template<typename Head, typename... Tail>
void capture(std::ostream& out, Head&& head, Tail&&... tail)
{
    out << std::forward<Head>(head) << ',';
    capture(out, std::forward<Tail>(tail)...);
}

template<typename... Args>
std::string abc(Args&&... args)
{
    std::ostringstream out;
    capture(out, std::forward<Args>(args)...);

    return out.str();    
}

Upvotes: 0

littleadv
littleadv

Reputation: 20282

This is compiler dependent and while theoretically you can do that, in practice it is likely not to be portable. You can do it at a compile time through macros, as @Tony mentioned, but for run-time - use the va_arg. It basically implements what you want, and is a tool provided by the standard to interface to this compiler-dependent functionality.

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106236

As best I can understand your requirement, it is not possible in Standard C++03. The most closely related C++ functionality is preprocessor macro argument stringification, which would allow something like this:

#define ABC(X) do { remember_string_version(#X); abc X; } while (false)

ABC(("%d %d %d how are you",1,2,3));

Note the double parenthesis - these group the string and numbers so they match the a single parameter "X" expected by ABC.

Preprocessor stringification is the only facility that lets you preserve some snippet of source code as a string, while still using it as source code....

Upvotes: 2

Related Questions