正常
Variadic Templates (C++11)
One-Liner
Lets templates accept any number of arguments of any type — the modern, type-safe replacement for C-style variadics (va_list).
Header
No header required (language feature)
Core API Cheat Sheet
| Operation | Signature | Description |
|---|---|---|
| Type parameter pack | typename... Ts | Accepts zero or more type parameters |
| Non-type parameter pack | Ts... args | Accepts zero or more non-type parameters |
| Template template parameter pack | template<typename> class... Ts | Accepts zero or more templates |
| Parameter pack expansion | args... | Expands the parameter pack into multiple expressions |
| Parameter pack size | sizeof...(args) | Returns the number of elements in the parameter pack |
| Fold expression | (args op ...) / (... op args) | C++17, applies an element-wise operation to the pack |
Minimal Example
C++
// Standard: C++11
#include <iostream>
template<typename... Ts>
void print(Ts... args) {
// Use an initializer list to print the arguments one by one, in order
int dummy[] = {(std::cout << args << " ", 0)...};
(void)dummy;
}
int main() {
print(1, "hello", 3.14);
}Embedded Applicability: Medium
- Can fully replace the unsafe
va_list, improving type safety and code maintainability - Template instantiation causes code bloat (larger binary size), so keep an eye on Flash usage
- A good fit for resource-richer settings (e.g., application processors running Linux); needs careful evaluation on low-end bare-metal MCUs
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 4.3 | 2.9 | TBD |
See Also
Some content is adapted from cppreference.com, used under the CC-BY-SA 4.0 license