Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a string with delimeters from fold expression [duplicate]

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?

like image 558
original.roland Avatar asked Apr 10 '19 05:04

original.roland


1 Answers

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

like image 134
Yashas Avatar answered Oct 27 '22 17:10

Yashas