Search⌘ K
AI Features

Solution: Concatenate Strings

Explore how to use variadic templates in C++ to concatenate multiple strings dynamically. Understand the implementation of the strOps class, fold expressions, and auxiliary functions that manage string concatenation and character counting. This lesson provides detailed insights into leveraging templates for flexible and efficient string handling.

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.

C++ 17
#include <iostream>
#include <string>
template<typename... Strings>
class strOps {
public:
// Constructor to concatenate strings and calculate information
strOps(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 template
template<size_t... R>
static constexpr size_t Counts = (R + ...);
// Helper function to concatenate strings using fold expression
template<typename... Args>
std::string concatenate(const Args&... args) {
return (args + ...);
}
// Helper function to count total characters in a string
int count_characters(const std::string& str) {
return str.length();
}
};
// Variadic function template to display information
template<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: ...