Skip to content

Variadic Templates (C++11)

In a Nutshell

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

None required (language feature)

Core API Quick Reference

OperationSignatureDescription
Type parameter packtypename... TsAccepts zero or more type arguments
Non-type parameter packTs... argsAccepts zero or more non-type arguments
Template template parameter packtemplate<typename> class... TsAccepts zero or more templates
Parameter pack expansionargs...Expands a parameter pack into multiple expressions
Parameter pack sizesizeof...(args)Returns the number of elements in the parameter pack
Fold expression(args op ...) / (... op args)C++17, applies a per-element operation over a parameter pack

Minimal Example

cpp
// Standard: C++11
#include <iostream>

template<typename... Ts>
void print(Ts... args) {
    // 利用初始化列表保证顺序地逐个打印
    int dummy[] = {(std::cout << args << " ", 0)...};
    (void)dummy;
}

int main() {
    print(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 we need to monitor Flash usage
  • Suitable for resource-rich scenarios (such as application processors running Linux); requires careful evaluation on bare-metal, low-end MCUs

Compiler Support

GCCClangMSVC
4.32.9TBD

See Also


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress