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..
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With