8

I've got the following function:

template<typename... Args>
void Foo(Args && ... args)
{
    std::stringstream stream;
    (stream << ... << args);
    // Do somethign with it
}

It can perfectly concat params into a string, but as expected it gives the output without any delimiter. Is it possible to somehow delimit the inputs from each other?

Sample output:

elg.Debug("asd", "qwe", 123);

// Prints: asdqwe123

// Should prints something LIKE: asd qwe 123

Do I have to roll my own stringstream replacement for this?

Community
  • 1
  • 1
original.roland
  • 640
  • 5
  • 17
  • 1
    If you want "output" with a specific separator, then perhaps using [`std::ostream_iterator`](https://en.cppreference.com/w/cpp/iterator/ostream_iterator) would be better? – Some programmer dude Apr 10 '19 at 05:57

1 Answers1

15

With trailing delimiter:

template<typename... Args>
void debug(Args&& ... args)
{   
    std::ostringstream stream;
    ((stream << args << ' '), ...);
}

Without trailing delimiter:

template<typename FirstArg, typename... Args>
void debug(FirstArg&& firstArg, Args&& ... args)
{   
    std::ostringstream stream;
    stream << firstArg;
    ((stream << ", " << args), ...);
}

If the race is to have the shortest code, then last two lines can be merged into one: stream << firstArg, ((stream << ", " << args), ...);.


#include <iostream>

template<typename... Args>
void debug(Args&& ... args)
{   
    ((std::cout << args << ' '), ...);
}

int main () {
    debug("asd", 112, 0.04);
    return 0;   
}

Output: asd 112 0.04

Yashas
  • 1,154
  • 1
  • 12
  • 34