How to write a variational function for any amount of string concatenation in C ++

I am new to C ++. I know this is a very common question, but I want the full code to concatenate any number of lines that are passed to the function in C ++. I call the function the following:

string var1,var2;
var1=concat_string("one","two");
cout<<var1<<endl;
var2=concat_string("one","two","three");
cout<<var2<<endl;

My required result:

onetwo
onetwothree

I read about a variational function, but I tried the following code to concatenate strings, without worrying about the size of the result and the number of string arguments. My code is:

#include <cstdarg>
template<typename... T>
string concat_string(T const&... t){
    std::stringstream s;
    s<<t;
    return s;
}

But I have a lot of errors in this code. How can I fix my code. Thank..

+4
source share
2 answers

In C ++ 17 with a fold expression, this will be

template<typename... Ts>
string concat_string(Ts const&... ts){
    std::stringstream s;
    (s << ts << ...);
    return s.str();
}

( ++ 11) - , , :

template<typename... Ts>
string concat_string(Ts const&... ts){
    std::stringstream s;
    int dummy[] = {0, ((s << ts), 0)...};
    static_cast<void>(dummy); // Avoid warning for unused variable
    return s.str();
}
+6

, ++ 11, @Jarod42 :

template <typename... T>
std::string concat_string(T&&... ts) {
  std::stringstream s;
  int dummy[] = { 0, ((s << std::forward<T>(ts)), 0)... };
  static_cast<void>(dummy); // Avoid warning for unused variable
  return s.str();
}

rvalue - ++ 11, .

+2

Source: https://habr.com/ru/post/1684279/


All Articles