Merging Two Compile-Time Integer Sequences in C++
BehavioralModel answerLast updated
Combine two std::index_sequence types into one using template metaprogramming without deep recursion.
Problem Statement
You need to build a compile-time utility that merges two std::index_sequence types into a single sequence containing all integers from both inputs in order.
Implement:
- A struct template
concat_sequencesthat performs the merge - A type alias
concat_sequences_tfor convenient access to the result type
Requirements
- Use C++14 or later standard library features
- Handle empty sequences properly (merging an empty sequence with
{0, 1, 2}yields{0, 1, 2}) - Avoid deep template recursion—your approach should work efficiently with sequences containing up to 100 elements
Example Behavior
// Given these two sequences:
using First = std::index_sequence<0, 1, 2>;
using Second = std::index_sequence<3, 4>;
// The merged result should be:
using Merged = concat_sequences_t<First, Second>;
// Merged is equivalent to std::index_sequence<0, 1, 2, 3, 4>
Starting Point
#include <utility>
template <typename Seq1, typename Seq2>
struct concat_sequences;
template <typename Seq1, typename Seq2>
using concat_sequences_t = typename concat_sequences<Seq1, Seq2>::type;
Your task is to complete this implementation so it correctly merges the sequences.
Hints
Hint 1
Consider using partial template specialization to extract the integer packs from each index_sequence.
Hint 2
You can expand multiple parameter packs in a single template argument list.
Hint 3
Empty parameter packs are valid—they expand to nothing, requiring no special handling.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Approach
The core insight is that std::index_sequence<I...> is simply a type carrying a compile-time pack of integers. To merge two sequences, we use partial template specialization to extract both packs, then re-expand them consecutively in a new type.
The strategy:
- Leave the primary template undefined (it will only match invalid inputs)
- Create a partial specialization matching
std::index_sequence<I1...>, std::index_sequence<I2...> - In the specialization, deduce both packs and create
std::index_sequence<I1..., I2...>as the result
This avoids recursion entirely—we perform the merge in a single template instantiation.
Solution
#include <utility>
#include <type_traits>
// Primary template: undefined, causes compile error for non-sequence arguments
template <typename Seq1, typename Seq2>
struct concat_sequences;
// Specialization: extract both packs and expand them sequentially
template <std::size_t... I1, std::size_t... I2>
struct concat_sequences<std::index_sequence<I1...>, std::index_sequence<I2...>> {
using type = std::index_sequence<I1..., I2...>;
};
template <typename Seq1, typename Seq2>
using concat_sequences_t = typename concat_sequences<Seq1, Seq2>::type;
// Verification
static_assert(std::is_same<
concat_sequences_t<std::index_sequence<0, 1, 2>, std::index_sequence<3, 4>>,
std::index_sequence<0, 1, 2, 3, 4>
>::value, "basic merge failed");
static_assert(std::is_same<
concat_sequences_t<std::index_sequence<>, std::index_sequence<1, 2>>,
std::index_sequence<1, 2>
>::value, "empty first sequence failed");
static_assert(std::is_same<
concat_sequences_t<std::index_sequence<1, 2>, std::index_sequence<>>,
std::index_sequence<1, 2>
>::value, "empty second sequence failed");
int main() {}
Why This Works
Template Deduction: When the compiler encounters concat_sequences<std::index_sequence<0, 1>, std::index_sequence<2, 3>>, the partial specialization matches, binding I1... to {0, 1} and I2... to {2, 3}.
Pack Expansion Order: The expression I1..., I2... expands both packs in sequence. This preserves the internal order of each pack while placing the first before the second—exactly what concatenation requires.
Empty Sequences: Parameter packs can be empty. When I1... or I2... is empty, it expands to nothing. No special cases needed.
No Recursion: This solution uses exactly one template instantiation regardless of sequence size. There's no recursive nesting, so it easily handles sequences with 100+ elements without hitting compiler depth limits.
Complexity
- Template instantiation depth: O(1)—just one specialization, no recursion
- Compile-time cost: O(N + M) where N and M are the sequence lengths; the compiler must construct a type with N + M template arguments
- Runtime cost: None—everything happens at compile time; no code is generated
Edge Cases and Gotchas
Empty sequences: Both empty, one empty, or neither—all handled automatically by pack expansion rules.
Order preservation: Values remain in their original order, including duplicates or unsorted values. Merging {3, 1} with {2, 0} correctly yields {3, 1, 2, 0}.
Invalid inputs: If you pass something other than two std::index_sequence types (like int or a single sequence), you get a compile error because the primary template is undefined.
std::integer_sequence variants: This solution specifically handles std::index_sequence (which uses std::size_t). For other value types like int, you'd need a more general specialization that deduces the value type parameter.
Common Mistakes
- Attempting recursion: Writing a recursive solution that peels off one element at a time creates O(N) instantiation depth and is dramatically slower
- Forgetting
typename: The alias needstypename concat_sequences<...>::typesincetypeis a dependent name - Not testing empty cases: Many candidates forget to verify behavior with empty sequences
- Incorrect pack syntax: Writing
I1, ..., I2, ...instead ofI1..., I2...
Extension: Generalizing to std::integer_sequence
To support sequences with any value type (not just std::size_t), deduce the value type:
template <typename T, T... I1, T... I2>
struct concat_sequences<std::integer_sequence<T, I1...>,
std::integer_sequence<T, I2...>> {
using type = std::integer_sequence<T, I1..., I2...>;
};
Since std::index_sequence<I...> is an alias for std::integer_sequence<std::size_t, I...>, this generalized version automatically handles index sequences too.