Skip to content

Variadic Templates (C++11)

One-Liner

Allows templates to accept an arbitrary number of arguments of arbitrary types, serving as a type-safe modern alternative to C-style variadic functions (...).

None required (language feature)

Core API Cheat Sheet

OperationSyntaxDescription
Type parameter packtypename... TsAccepts zero or more type arguments
Non-type parameter packint... IsAccepts zero or more non-type arguments
Template template parameter packtemplate<typename> class... TemplatesAccepts zero or more templates
Parameter pack expansionTs...Expands the parameter pack into multiple expressions
Parameter pack sizesizeof...(Ts)Returns the number of elements in the parameter pack
Fold expression (unary)(expr op ...)C++17, performs per-element operation on the pack
Fold expression (binary)(init op ... op expr)C++17, performs per-element operation on the pack

Minimal Example

cpp
// 打印所有参数的函数
// Function to print all arguments
template <typename... Ts>
void print_all(Ts... args) {
    ((std::cout << args << " "), ...); // C++17 折叠表达式 (Fold expression)
}

int main() {
    print_all(1, "Hello", 3.14); // 输出: 1 Hello 3.14
}

Embedded Applicability: Medium

  • Can completely replace unsafe va_list, improving type safety and code maintainability.
  • Template instantiation causes code bloat (increased binary size), so monitor Flash usage.
  • Suitable for resource-rich scenarios (e.g., application processors with Linux); careful evaluation is needed on bare-metal low-end MCUs.

Compiler Support

GCCClangMSVC
4.32.9TBD

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05