Katkat

Concatenate Two C++ Index Sequences at Compile Time

SquarepointRisk Technology Software Engineer · Technical Screen

Last updated

This problem tests your mastery of C++ variadic templates, template metaprogramming, and the `std::index_sequence` utility to perform type-level list manipulation.

Problem Statement

In modern C++, template metaprogramming often requires manipulating sequences of integers at compile time. Your task is to implement a utility concat_sequences that takes two std::index_sequence types and returns a new std::index_sequence containing all elements from the first sequence followed by all elements from the second.

You must provide:

  1. A template alias concat_sequences_t that evaluates to the resulting sequence.
  2. The underlying struct template concat_sequences.

Constraints

  • You may use C++14 features (std::index_sequence, std::make_index_sequence, std::integer_sequence).
  • Do not use recursive template instantiation that exceeds typical compiler depth limits for sequences up to size 100.
  • Your solution should handle empty sequences correctly (e.g., concat(empty, {1, 2}) -> {1, 2}).

Example

// Input
using Seq1 = std::index_sequence;
using Seq2 = std::index_sequence;

// Result
using Result = concat_sequences_t;
// Result is std::index_sequence

Implementation Template

#include 

template 
struct concat_sequences;

template 
using concat_sequences_t = typename concat_sequences::type;

Hints

Hint 1

Consider specializing `concat_sequences` by extracting the template parameters of `std::index_sequence` using a variadic pack.

Hint 2

You can use a helper struct to unpack the packs from both sequences into a single `std::index_sequence` template instantiation.

Hint 3

Think about how `std::index_sequence` can be expanded into `std::index_sequence` using pack expansion.

Follow-up questions

  • How would you modify your solution to support appending a single integer to an existing index sequence?
  • What are the compile-time performance implications of using recursive template specialization versus pack expansion in C++17?
  • Can you implement a version of this that works with `std::integer_sequence` to handle arbitrary integer types?