Conceptresearch
Variadic generics
Also called variadic templates, parameter packs, template parameter pack, type parameter pack, TypeVarTuple, variadic tuple types, fold expression, sizeof....
Variadic generics let a generic function or type take any number of type parameters, as C++ parameter packs do, instead of one overload for each count of types.
- Applies to
- core-languages
Idea
Some generic code takes a list of types whose length is not fixed: a tuple of any size, a function with any number of parameters, a zip of any number of lists. With one type parameter for each type, a library needs one declaration for each count. Variadic generics let one declaration take a list of type parameters of any length.
#include <iostream>
#include <string>
#include <tuple>
// Ts is a pack: zero or more types.
template <typename... Ts>
std::size_t count_types(const Ts&...) {
return sizeof...(Ts);
}
int main() {
std::cout << count_types() << " " << count_types(1, "two", 3.0) << "\n";
std::tuple<int, std::string, double> t{1, "two", 3.0};
std::cout << std::tuple_size_v<decltype(t)> << "\n";
}
0 3
3
typename... Ts declares a template parameter pack. One template covers calls with zero, one or many arguments, each of its own type. std::tuple is a variadic class template, so std::tuple<int, std::string, double> has three type arguments.
How it works
Parameter packs. In C++, "A template parameter pack is a template parameter that accepts zero or more template arguments (non-types, types, or templates)."1 "A function parameter pack is a function parameter that accepts zero or more function arguments."1 "A template with at least one parameter pack is called a variadic template."1 Variadic templates "take a variable number of type parameters"2.
Using a pack. The program expands a pack: f(xs...) passes every element, and sizeof...(Ts) gives the number of elements1. A fold expression "Reduces (folds) a pack over a binary operator."3 (xs + ...) adds all the elements. A template can also handle the first element and call itself with the rest.
Other languages. Python added type variable tuples for static checkers. PEP 646 introduces TypeVarTuple, "enabling parameterisation with an arbitrary number of types"4, and the typing documentation calls it "A specialized form of type variable that enables variadic generics"5. TypeScript has variadic tuple types: "spreads in tuple type syntax can now be generic"6, so a type such as [...T, ...U] joins two tuple types. Swift added type parameter packs and value parameter packs "to enable abstracting over the number of types and values with distinct type"7.
The workaround: one declaration for each count. A language without variadic generics writes the same declaration many times. .NET has a Func delegate for each number of parameters up to 16; the largest one "Encapsulates a method that has 16 parameters"8. In Rust, some traits "are only implemented on tuples of arity 12 or less"9, and the code for each size is written by a macro. The Swift proposal describes these "ad-hoc variadic APIs with an arbitrary upper bound, typically achieved with overloads that each have a different fixed number of type parameters and corresponding arguments"7.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Absent | A varargs parameter takes any number of values of one type, and a generic type has a fixed number of type parameters. Alternative: One interface or class for each number of type parameters, or a list of values of a common supertype. |
| C | Does not apply | C has no generics. A variadic function with va_list takes any number of arguments, with no types. |
| C# | Absent | A params parameter takes any number of values of one type, and a generic type has a fixed number of type parameters. Alternative: One overload for each number of type parameters, as the Func and Action delegates do, or a ValueTuple. |
| JavaScript | Does not apply | JavaScript has no type parameters. A rest parameter takes any number of values, with no types. |
| TypeScript | Native | |
| Go | Absent | A variadic parameter takes any number of values of one type, and a generic function has a fixed number of type parameters. Alternative: One function for each number of type parameters, or a slice of an interface type. |
| Rust | Absent | |
| Kotlin | Absent | A vararg parameter takes any number of values of one type, and a generic type has a fixed number of type parameters. Alternative: One declaration for each number of type parameters. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A query has no type parameters. |
| Bash | Does not apply | Bash has no types for its values. |
| PowerShell | Does not apply | A PowerShell script cannot declare its own generic code. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no types of values. |
| CSS | Does not apply | CSS has no types in this sense. |
| Regular expressions | Does not apply | A regular expression has no types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | TypeVarTuple and [*Ts], for static checkers |
| JavaScript | n/a | the language has no type parameters |
| TypeScript | native | variadic tuple types, such as [...T, ...U] |
| Java | absent | varargs T... take many values of one type; no list of type parameters |
| Kotlin | absent | vararg takes many values of one type; no list of type parameters |
| C# | absent | params takes many values of one type; Func and Action have one overload for each count |
| Go | absent | variadic parameters ...T take many values of one type |
| Rust | absent | tuples and macros that write an impl for each tuple size |
| C | n/a | the language has no generics; va_list functions have no types for their arguments |
| C++ | native | template parameter packs, pack expansion, sizeof... and fold expressions |
| Bash | n/a | the language has no types |
| PowerShell | n/a | a script cannot declare its own generic code |
| SQL | n/a | a query has no type parameters |
| Regex | n/a | a pattern has no types |
| HTML | n/a | HTML has no types |
| CSS | n/a | CSS has no types of this kind |
"While other languages, such as Java or C# offer support for type-safe variadic functions, they do not offer the variadic generics support like that of C++ and D."2 A varargs parameter takes any number of values of one type. Variadic generics take any number of types.
The example files show C++ packs and fold expressions, Python TypeVarTuple, TypeScript variadic tuple types, and the Rust macro that writes one impl for each tuple size.
def to_tuple[*Ts](*args: *Ts) -> tuple[*Ts]:
return args
class Row[*Ts]:
def __init__(self, *cells: *Ts) -> None:
self.cells = cells
t = to_tuple(1, "a", 2.5) # a checker infers tuple[int, str, float]
print(t)
r: Row[int, str] = Row(7, "x")
print(r.cells, to_tuple.__type_params__)
(1, 'a', 2.5)
(7, 'x') (Ts,)
- Verdict: native.
*Tsdeclares a type variable tuple, soto_tupleandRowtake any number of type arguments. A type checker inferstuple[int, str, float]fort. Python does not check these types when the program runs.
#include <iostream>
#include <string>
#include <tuple>
// A fold expression over a pack of values.
template <typename... Ts>
auto sum(Ts... xs) {
return (xs + ... + 0);
}
template <typename... Ts>
void print_all(const Ts&... xs) {
((std::cout << xs << " "), ...);
std::cout << "(" << sizeof...(Ts) << " values)\n";
}
int main() {
std::cout << sum(1, 2, 3.5) << " " << sum() << "\n";
print_all(1, std::string("two"), 3.5);
std::tuple<int, char, double> t{1, 'x', 2.5};
auto n = std::apply([](auto... xs) { return sizeof...(xs); }, t);
std::cout << n << "\n";
}
6.5 0
1 two 3.5 (3 values)
3
- Verdict: native.
typename... Tsis a template parameter pack andTs... xsis a function parameter pack.(xs + ... + 0)folds the pack with+, andsizeof...counts its elements.std::applyexpands a tuple into a pack of arguments.
function concat<T extends unknown[], U extends unknown[]>(a: [...T], b: [...U]): [...T, ...U] {
return [...a, ...b];
}
function tail<T extends unknown[]>(arr: readonly [unknown, ...T]): T {
const [, ...rest] = arr;
return rest as T;
}
const joined = concat([1, "a"], [true]); // [number, string, boolean]
const rest = tail([0, "x", false] as const); // ["x", false]
console.log(joined, joined.length);
console.log(rest);
[ 1, 'a', true ] 3
[ 'x', false ]
- Verdict: native.
TandUstand for tuple types of any length, and[...T, ...U]joins them, so the checker knows the type of each element ofjoined. The types are removed before the program runs.
trait Arity {
fn arity() -> usize;
}
// One impl for each tuple size, written by a macro.
macro_rules! impl_arity {
($($name:ident),+) => {
impl<$($name),+> Arity for ($($name,)+) {
fn arity() -> usize {
[$(stringify!($name)),+].len()
}
}
};
}
impl_arity!(A);
impl_arity!(A, B);
impl_arity!(A, B, C);
fn main() {
println!(
"{} {} {}",
<(i32,)>::arity(),
<(i32, &str)>::arity(),
<(u8, u8, u8)>::arity()
);
}
1 2 3
This code does not compile, on purpose.
fn main() {
let t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
println!("{:?}", t);
}
- Verdict: absent. Rust has no type parameter packs. The macro writes one
implfor each size, and the trait has noimplfor sizes that the macro did not write. The standard library does the same forDebug, so a tuple with 13 elements cannot be printed with{:?}.
Variations and related ideas
- Packs of values. C++ packs can hold values, such as
template <int... Ns>, and template templates as well as types1. - Tuples as the workaround. A function that takes one tuple of any type can stand for a function with many parameters. The code still needs one declaration for each tuple size, so libraries stop at a fixed size, such as 12 in Rust9 or 16 in .NET8.
- Variadic functions. A variadic function, such as
printfin C, takes any number of arguments with no types. Before variadic templates, C++ "variadic functions could only be implemented using va_list or variadic macros from C, which lack type safety"2.
Pitfalls
- A limit on the size. Code that uses overloads or macros for each size has a largest size. A Rust tuple with 13 elements does not implement
Debug, because the trait is implemented only up to 129. - Recursion in the compiler. A C++ pack processed by recursion makes one instantiation for each element. Use a fold expression or a pack expansion where you can.
- A pack is not a value. In C++, a pack is not a tuple. The program cannot store it in a variable; it expands it or puts it in a
std::tuple. - Checks only in the checker. In Python and TypeScript, the types of a variadic generic are checked only by the type checker.
History
The variadic template feature of C++ "was designed by Douglas Gregor and Jaakko Järvi"2, and before it, "templates (classes and functions) could only take a fixed number of arguments"2. PEP 646 was created on 16 September 20204. The Swift proposal calls packs "the first step toward variadic generics in Swift"7.
References
- Pack, C++ reference, cppreference.com, Introduction; Pack expansion; The sizeof... operator
- Variadic template, Wikipedia, Introduction; C++
- Fold expressions, C++ reference, cppreference.com, Introduction
- PEP 646, Variadic Generics, Abstract
- typing, Python 3.14 documentation, TypeVarTuple
- TypeScript 4.0, release notes, Variadic Tuple Types
- SE-0393, Value and Type Parameter Packs, Swift Evolution, Introduction
- Func<T1,...,T16,TResult> Delegate, .NET API, Definition
- Primitive Type tuple, Rust standard library, Trait implementations
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag EG09QP Edit this page History Report an error Markdown