TMP how to generalize a Cartesian Product of Vectors?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
If you only have two vectors, a Cartesian product is easy to write with two nested loops. The real problem is making the same idea work for an arbitrary number of vectors without hardcoding loop depth.
In modern C++, the clean approach is to use variadic templates for type generality and a recursive helper for runtime enumeration. That gives you one function that works for any number of input vectors and returns tuples containing one choice from each vector.
What Needs To Be Generalized
For vectors A, B, and C, the Cartesian product contains every tuple:
- one element from
A - one element from
B - one element from
C
The number of outputs is the product of the input sizes, so the challenge is not asymptotic magic. The challenge is expressing "nested loops of arbitrary depth" in reusable code.
A Variadic Template Solution
The example below stores the current partial tuple and recursively fills one position at a time.
This is generic across element types and across vector count. The recursion happens over tuple indices rather than over handwritten loops.
Why TMP Helps Here
Template metaprogramming is useful because the number and types of vectors are known at compile time. That lets the compiler build:
- the tuple type for one output row
- the tuple of input vector references
- the recursive instantiations for each position
The values themselves are still runtime data. TMP is not being used to compute the entire Cartesian product at compile time. It is being used to generate a type-safe generalized algorithm.
Design Tradeoffs
This approach is clean, but the cost is still real:
- output size grows multiplicatively
- memory usage can explode if you materialize all tuples
- compile errors can be harder to read than in a handwritten two-vector version
If you only need to visit combinations one at a time, a callback-based generator can be better than building a giant std::vector<Tuple>.
When a Callback Is Better
For large products, replace output.push_back(current) with a function call such as visitor(current). That lets you process each tuple immediately instead of storing the full product in memory.
This is often the right design for search, filtering, or streaming pipelines where most combinations are discarded quickly.
Common Pitfalls
- Confusing compile-time type generalization with compile-time generation of all values.
- Materializing the full Cartesian product when the result set is enormous.
- Hardcoding homogeneous element types when the problem really needs tuples of mixed types.
- Writing nested loops manually and losing scalability beyond two or three vectors.
- Ignoring the multiplicative output size and blaming templates for performance problems caused by the problem itself.
Summary
- The generalized Cartesian product problem is really "nested loops of arbitrary depth."
- Variadic templates and tuple recursion provide a clean C++ solution.
- TMP helps build a type-safe generic algorithm, even though the values are produced at runtime.
- Returning all tuples is convenient but can consume a lot of memory.
- For large products, a visitor or generator style is often the better design.
Related reading
- To make a distance matrix or to repeatedly calculate distance
- Topological sort of cyclic graph with minimum number of violated edges
- total area of intersecting rectangles
- Transform 3D Tensor to 4D
- Transform sparse matrix to tensor
- Transformation between two set of points
- Traveling salesman example with known global optimum
- Travelling Salesman with multiple salesmen?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.