Parameter Packing and Varadic Templates
String concatenation with varadic templates
c++
template <std::string_view const&... Args>
class Concat {
public:
static constexpr auto impl() noexcept {
constexpr std::size_t len = (Args.size() + ... + 0);
std::array<char, len + 1> arr{};
auto append = [i = 0, &arr](auto const& s) mutable {
for (auto c : s) arr[i++] = c;
};
(append(Args), ...);
arr[len] = 0;
return arr;
}
// Give the joined string static storage
static constexpr auto arr = impl();
// View as a std::string_view
static constexpr std::string_view value {arr.data(), arr.size() - 1};
};
template <std::string_view const&... Args>
static constexpr auto concat = Concat<Args...>::value;
constexpr std::string_view OUTPUT = concat<STR1,STR2,STR3>;
template <std::string_view const&... Args>
class Concat {
public:
static constexpr auto impl() noexcept {
constexpr std::size_t len = (Args.size() + ... + 0);
std::array<char, len + 1> arr{};
auto append = [i = 0, &arr](auto const& s) mutable {
for (auto c : s) arr[i++] = c;
};
(append(Args), ...);
arr[len] = 0;
return arr;
}
// Give the joined string static storage
static constexpr auto arr = impl();
// View as a std::string_view
static constexpr std::string_view value {arr.data(), arr.size() - 1};
};
template <std::string_view const&... Args>
static constexpr auto concat = Concat<Args...>::value;
constexpr std::string_view OUTPUT = concat<STR1,STR2,STR3>;
ADDITIONAL RESOURCES