6

I am a newbie in c++. I know this is a very common question, but I want a complete code to concat any number of strings which are passed to function in c++. I am calling the function as:

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

My required output is:

onetwo
onetwothree

I have read about variadic function, but I tried the following code to concatenate strings without worrying of the result size and 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 got lots of error in this code. How can I correct my code. Thanks..

M. Paul
  • 361
  • 5
  • 18
  • 1
    you can simply do `std::string("one")+"two"+"three";` I dont think this is a common question, because you dont need such a function...Is this an exercise? – 463035818_is_not_an_ai Aug 23 '17 at 07:53
  • @tobi303 Thank you for a simple and nice solution. It works fine. But actually I just wanted to learn variadic function procedure for string concatenation, so that I can apply this procedure in some other application. – M. Paul Aug 23 '17 at 09:32

2 Answers2

8

In C++17, with fold expression, it would be

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

Previously (but since C++11), you have to rely on some trick to have a valid expansion context, such as:

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();
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
2

Since it looks like you're learning C++11, here's a minor extension of @Jarod42's excellent solution to support perfect forwarding:

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();
}

Perfect forwarding and rvalue references is another feature in C++11 that can result in improved performance.

rustyx
  • 80,671
  • 25
  • 200
  • 267