KatInterview

Merging Two Compile-Time Integer Sequences in C++

BehavioralModel answer
MediumModel answerBehavioralc++templatesmetaprogramming

Last 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:

  1. A struct template concat_sequences that performs the merge
  2. A type alias concat_sequences_t for 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.