Skip to content

Instantly share code, notes, and snippets.

@AlexisTM
Last active February 28, 2023 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexisTM/a993646ea013f9b7ef061276f5b86177 to your computer and use it in GitHub Desktop.
Save AlexisTM/a993646ea013f9b7ef061276f5b86177 to your computer and use it in GitHub Desktop.
Variadic template string and string_view concat for C++17
#include <string>
// concat(a,b,c) is the equivalent to std::string(a) + std::string(b) + std::string(c)
template<class T>
std::string concat(T t) {
return std::string(t);
}
template<class T, class... Types>
std::string concat(T t, Types&&... others) {
return concat(t) + concat(others...);
}
// The concat2 implementation is 250% faster because it avoids creating many new string instances that are directly deleted.
// concat2(a,b,c) is the equivalent of:
// std::string output;
// output.append(a);
// output.append(b);
// output.append(c);
// The benchmark: https://quick-bench.com/q/nC45fivQ3TIRXMysQ3hJwC5oSsw
template<class T>
void append_to_str(std::string& inout, T t) {
inout.append(t);
}
template<class T, class... Types>
void append_to_str(std::string& inout, T t, Types&&... others) {
append_to_str(inout, t);
append_to_str(inout, others...);
}
template<class T>
std::string concat2(T t) {
return std::string(t);
}
template<class T, class... Types>
std::string concat2(T t, Types&&... others) {
std::string output;
output.append(t);
append_to_str(output, others...);
return output;
}
constexpr std::string_view hello = "Hello";
constexpr const char* world = "world";
const std::string cpp = "C++!";
int main() {
std::string res = concat(hello, " ", world, " ", cpp);
std::string res2 = concat2(hello, " ", world, " ", cpp);
printf("%s", res.c_str());
printf("%s", res2.c_str());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment