Task:

  • Accept in function an indefinite number of elements with different types.
  • Shove everything up in stringstream

Question:

  • How to open a list of arguments and shove in stringstream?

Maybe you need to use other tools for this task? Please tell ostream which ones (please, ostream not offer the option with ostream )?

  template<typename ... Arguments> void tfunc(const Arguments & ... args) { std::stringstream ss; //ss<<args; } 

    3 answers 3

    This is easily done with the fold expression:

     template<typename ... Arguments> void tfunc(Arguments const & ... args) { std::stringstream ss; (ss << ... << args); } 

    online compiler

    • And do not tell me - I feel something bad for them so far - how through them (fold expression) to output, say, with a space between them, or with some other action (well, simplicity for - count without using sizeof... ) ? - Harry
    • By the way, don’t you tell me (I’m not quite new to this topic), why is there no separate, so to speak, final function? Tobish when we have only one argument left ... - Andrej Levkovitch
    • VS 2017 does not digest, writes 'error C2760: syntax error: expected token "<No data>", and not "<No data>"' - Duracell
    • 2
      @Harry You can define an operation and unpack it, for example output with auto Print{[&ss, pp{0}](auto && arg) mutable { ::std::cout << "#" << (pp++) << " " << arg << " "; }}; (Print(args), ...); sequence numbers auto Print{[&ss, pp{0}](auto && arg) mutable { ::std::cout << "#" << (pp++) << " " << arg << " "; }}; (Print(args), ...); auto Print{[&ss, pp{0}](auto && arg) mutable { ::std::cout << "#" << (pp++) << " " << arg << " "; }}; (Print(args), ...); : online compiler . - VTT
    • one
      @Duracell Make sure you have version 15.8.4, and builds with the /std:c++17 flags /std:c++17 /permissive- - VTT

    You can use a temporary array to decompress a parameter package.

     template<typename ... Args> std::string foo(Args const & ... args) { std::stringstream ss; using arr_t = int[sizeof...(args)];//Тип массива для удобства arr_t{((ss << args << ' '), 0)...};//Создаем временный массив return ss.str(); } 
    • This method is good for C ++ 14 and older versions, where there is no fold expressions. Clearly better recursion, which is offered in the next post. By the way, int[sizeof...(args)] can be replaced by int[] . - HolyBlackCat
    • one
      @HolyBlackCat option with fold expression already written, but maybe this one is useful. - Croessmah

    Well, for example, like this :

     void tfunc(stringstream&) {} template<typename T, typename ... Arguments> void tfunc(stringstream& s, T t, Arguments ... args) { s << t << " "; tfunc(s,args...); } int main(int argc, const char * argv[]) { stringstream s; tfunc(s,1,0.5,",,,"); cout << s.str() << endl; }