Skip to content

Instantly share code, notes, and snippets.

@Crspy
Last active November 20, 2025 11:21
Show Gist options
  • Select an option

  • Save Crspy/ccc06da04408d80aed0143c180c0c653 to your computer and use it in GitHub Desktop.

Select an option

Save Crspy/ccc06da04408d80aed0143c180c0c653 to your computer and use it in GitHub Desktop.
C++17 constexpr strings concatenation
#include <type_traits>
#include <array>
#include <iostream>
template<typename first, typename... rest>
constexpr auto all_same_v = std::conjunction_v<std::is_same<first, rest>...>;
template <typename... Ts>
constexpr auto concat_strings(Ts&&... args) {
static_assert(all_same_v<std::decay_t<Ts>...>, "strings must be of the same char type");
using charType =
std::remove_const_t<std::remove_pointer_t<std::common_type_t<Ts...> > >;
constexpr size_t charCount =
((sizeof(Ts) + ...) - sizeof...(Ts) + sizeof(charType)) /
sizeof(charType);
std::array<charType, charCount> result{};
result[charCount - 1] = '\0';
size_t pos = 0;
auto detail_concat = [&pos, &result](auto&& arg) {
constexpr auto count = (sizeof(arg) - sizeof(charType)) / sizeof(charType);
for (size_t i = 0; i < count; ++i) {
result[pos++] = arg[i];
}
};
(detail_concat(args),...);
return result;
}
int main() {
constexpr auto str = concat_strings(L"this ", L"is ", L"compile-time ", L"string ", L"concatenation");
std::wcout << str.data();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment