Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write variadic function for any number of string concatenation in c++

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..

like image 278
M. Paul Avatar asked Aug 23 '17 07:08

M. Paul


2 Answers

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();
}
like image 144
Jarod42 Avatar answered Sep 28 '22 09:09

Jarod42


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.

like image 21
rustyx Avatar answered Sep 28 '22 09:09

rustyx