Solution: Concatenate Strings
Learn about the process used to solve the concatenate strings challenge.
We'll cover the following...
We'll cover the following...
Concatenating variable number of strings
Let’s first execute the following solution to concatenate a variable number of strings using variadic templates and see the code output. Then we’ll go through it line by line.
Press + to interact
C++ 17
#include <iostream>#include <string>template<typename... Strings>class strOps {public:// Constructor to concatenate strings and calculate informationstrOps(const Strings&... strings): Concatenated(concatenate(strings...)),TotalStrings(Counts<sizeof...(strings)>),TotalCharacters(count_characters(Concatenated)){}int get_count(){return TotalStrings;}int get_string_length(){return TotalCharacters;}std::string get_string(){return Concatenated;}private:std::string Concatenated;int TotalStrings;int TotalCharacters;// Counts total strings using variadic variable templatetemplate<size_t... R>static constexpr size_t Counts = (R + ...);// Helper function to concatenate strings using fold expressiontemplate<typename... Args>std::string concatenate(const Args&... args) {return (args + ...);}// Helper function to count total characters in a stringint count_characters(const std::string& str) {return str.length();}};// Variadic function template to display informationtemplate<typename... Ts>void display_info(Ts... ts) {((std::cout << ts ), ...) << '\n';}int main() {strOps<std::string, std::string, std::string, std::string, std::string>strConcatenator("Hello ", "world", " in C++", " template metaprogramming", "!");display_info("String: ", strConcatenator.get_string());display_info("Total characters: ", strConcatenator.get_string_length());display_info("Number of strings merged: ", strConcatenator.get_count());return 0;}
Explanation
Let’s go over how each code block works in the widget above.
Lines 1–2: ...