Abstract¶
Generic programming in C++ is a paradigm that enables writing flexible, reusable code by abstracting types and operations through templates. A template class defines a blueprint for classes parameterized by types, while a template function allows functions to operate on different types without rewriting code. Templates can have type parameters or non-type parameters, which represent compile-time constants. Templates can also be variadic using parameter packs, which allow an arbitrary number of parameters/arguments of different types to be specified in different contexts. Parameter pack can be expanded according to different patterns, for instance, using the folding expressions.
from __init__ import *
!mkdir -p private%%cpp
#include "utility.hpp"Motivation¶
Consider implementing the Python function print in C++:
print?Signature: print(*args, sep=' ', end='\n', file=None, flush=False)
Docstring:
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
Type: builtin_function_or_method*is an unpacking operator in Python. In*args,argsis a parameter pack that gets unpacked to a variable number of parameters, which takes the values of the positional arguments:
print(1, 2.0, 'c', "def") 1 2.0 c def
sep=' 'andend='\n'are optional keyword-only parameters which are specified as follows:
print(1, 2 ,3, sep=", ", end=";\n")1, 2, 3;
fileallows one to specify a file-like object to print to :
with open('private/python_output.txt', 'w') as f:
print("Hello,", "World!", file=f)
!cat private/python_output.txtHello, World!
We will learn how to implement print in C++.
Variadic Template¶
Parameter Pack¶
How to define a function that takes a variable number of arguments in C++?
Similar to * in Python, we can use ... to define a parameter pack:
%%writefile private/pack.cpp
#include <iostream>
using std::cout;
template <auto... pack>
auto foo() {
return sizeof...(pack);
}
int main() {
cout << foo<1, 2.0, 'c'>() << '\n';
return 0;
}Overwriting private/pack.cpp
!cd private && g++ -std=c++23 pack.cpp -o pack && ./pack3
In the above definition
auto... packis a named constant template parametertype ... name (optional)which can pack a variable number of non-type constants of structural type.
sizeof...is an operator that gives the number of arguments of the named packargs.
However, many types are not structural types, and we often want a function to take mutable arguments. For instance:
cout << foo<"def">() << '\n';fails because
"def"is not a valid template argument for typeconst char*. String literals cannot be used in this context.
const int a=rand(); cout << foo<a>() << '\n';fails because
ais not a constant expression.
%%hermes
Explain in a paragraph or two why the type for constant template parameter
must be a structural type? Why are C-string and random int not structural?🌿 Fork/new: main (will create on click)
Hermes
Why structural types. Template arguments are part of the program’s interface, not just its body: they sit in the template-id, drive overload resolution and specialization selection, and get baked into symbol names that must match across translation units at link time. So whatever you write as an argument has to denote exactly the same thing everywhere, wherever it’s spelled out — two TUs writing “the same” argument must produce identical instantiations and identical symbols. A structural type is precisely a type where an object’s identity is fully determined by its fields’ values, with comparison defined directly on those fields (and every field publicly accessible). If arbitrary types were allowed, two objects that “look” equal could differ in ways field-inspection can’t see — hidden state, volatile members, virtual dispatch — so equal arguments could instantiate to different code or link against different symbols, silently breaking overload resolution and the one-definition rule across TUs. That’s why template<auto... pack> may only pack constants whose meaning is fixed by value alone.
The two failures. They actually fail for subtly different reasons, but both hit that same root requirement of “pure value, known at compile time”:
"def"(cell above): a string literal is an array (const char[4]), and arrays can’t be non-type template parameters at all; and re-expressing it as a pointer would make its “value” an address that varies per translation unit and per build even for identical text — so two copies of"def"in different TUs wouldn’t be equal values, which is exactly what structural-ness exists to prevent. g++ agrees verbatim:'\"def\"' is not a valid template argument for type 'const char*' because string literals can never be used in this context.const int a = rand(); foo<a>()(cell below): here the typeintis perfectly admissible — what fails is the value.rand()is not constexpr, soahas no compile-time value; it only comes into existence at runtime, after deduction and instantiation already had to happen. g++:the value of 'a' is not usable in a constant expression.
This motivates the idea of function parameter pack:
%%writefile private/pack.cpp
#include <iostream>
using std::cout;
template <class... Ts>
auto foo(Ts... args) {
return sizeof...(args);
}
int main() {
cout << foo(1, 2.0, 'c', "def") << '\n';
return 0;
}Overwriting private/pack.cpp
!cd private && g++ -std=c++23 pack.cpp -o pack && ./pack4
In the above definition, class... Ts is a named type template parameter
type-parameter-key ... name (optional)where type-parameter-key is either class, or equivalently, typename. It packs a variable number of types, which is used in Ts... args to specify a named function parameter pack
pack-name ... pack-param-name (optional)which allows functions to take a variable number of arguments of possibly different types.
Pack Expansion¶
How to implement the print function?
Unfortunately, we cannot index a pack prior to the standard C++26.
%%hermes
Explain in a paragraph or two why elements of a parameter pack cannot be
extracted using subscription operation in C++.↻ Session: main (ACP: b7b3b8c2-34b…)
Hermes
There is no object to subscript. A parameter pack is not a container: in the lecture’s template <class... Ts> auto foo(Ts... args), args names N separate parameters that remain one unexpanded list until the compiler expands them. Subscripting requires an lvalue of array or class type with defined [] semantics, but no such single object exists — the elements are heterogeneous (1, 2.0, 'c', "def" in the demo) and share no storage, layout, or indexable structure. The grammar enforces this directly: outside a pack expansion, a pack is simply not usable, so writing return args[1]; fails with exactly error: parameter packs not expanded with '...'. And expansion isn’t indexing anyway — it duplicates a whole pattern N times in order (f(args...)), so it can’t pick out one specific element.
There was no way to say “the i-th”. Before C++26, the language’s entire toolkit for packs is sequential: ordered expansion into fixed syntactic contexts, or recursion peeling one element at a time via head, rest... deduction. Nothing can retrieve element i without unwrapping i times, and each element’s type is only known at instantiation time, so random access would have required expressions whose type depends on a compile-time index — which ordinary expressions can’t express. That’s why the working pre-C++26 idiom is to materialize the arguments into a real object first — e.g. std::tuple<Ts...> t{std::forward<Ts>(args)...}; then index with std::get<I>(t). The standard eventually added what the lecture’s cell above points at: pack indexing in C++26 (__cpp_pack_indexing), letting you index elements of a decomposed pack directly.
Nevertheless, we can access individual argument of a pack by pack expansion and recursion:
%%writefile private/print.cpp
#include <iostream>
using std::cout;
void print() {
cout << '\n';
}
template <class T, class... Ts>
void print(const T &first, const Ts &... rest) {
cout << first;
if (sizeof...(rest)) cout << ' ';
print(rest...);
}
int main() {
print(1, 2.0, 'c', "def");
return 0;
}Overwriting private/print.cpp
!cd private && g++ -std=c++23 print.cpp -o print && ./print1 2 c def
The base case with no argument is handled by
void print() { cout << '\n'; }
The recursive call
print(rest...)uses a function argument list, which is a simple pack expansionpattern ...that expands the pattern (containing at least one pack) into zero or more instantiations of the pattern, where the name of each pack is replaced by each of the elements from the pack, in order.
E.g., for the callprint(1, 2.0, 'c', "def");, the recursive callprint(rest...)is expanded toprint( 2.0, 'c', "def" // rest... );
In the function parameter pack
const Ts &... rest, pack expansion is also applied toconst Ts &...to expand the template parameter packclass... Ts.
E.g., for the callprint(1, 2.0, 'c', "def"), the compiler expands the function parameter pack as follows:void print( const int &, // const T &first, const double &, const char &, const char (&)[4] // const Ts &... rest );
Pack expansion can be used in various contexts. E.g., a simpler implementation of print is as follows:
%%cpp
void print(const auto &... args) {
((cout << args << ' '), ...);
cout << "\b\n";
};
print(1, 2.0, 'c', "def");1 2 c def
void print(const auto &... args) is an abbreviated function template equivalent to
template <class Ts>
void print(const Ts &... args)((cout << args << ' '), ...) is a unary right fold expression
(E op ...)which expands to
(E1 op (... op (EN-1 op EN)))where E1, E2, ..., EN are the instantiations of the pattern E with the actual list of parameters.
Solution to Exercise 1
The pattern E is (cout << args << ' ') and the operator op is the comma operator). Hence, the expansion is
(cout << 1 << ' '), ((cout << 2.0 << ' '), ((cout << 'c' << ' '), (cout << "def" << ' ')))An alternative implementation of print in one line is:
%%cpp
void print(const auto &... args) {
((cout << args << ' '), ..., (cout << "\b\n"));
};
print(1, 2.0, 'c', "def");1 2 c def
((cout << args << ' '), ..., (cout << "\b\n")); is a binary right fold expression
(E op ... op I)which expands to
(E1 op (... op (EN op I)))where E1, E2, ..., EN are the instantiations of the pattern E.
%%cpp
auto sum(const auto &... args) {
/*
### BEGIN SOLUTION
*/
// return (0 + ... + args); // left fold
return (args + ... + 0); // right fold
/*
### END SOLUTION
*/
}
cout << sum(1, 2, 3, 4) << '\n'; // 10 10
In C, there is an alternative way of defining a function with a variable number of arguments using the so-called variadic arguments:
%%cpp
int add_nums(int count...) // int add_nums(int count, ...)
{
int result = 0;
std::va_list args;
va_start(args, count);
for (int i = 0; i < count; ++i)
result += va_arg(args, int);
va_end(args);
return result;
}
std::cout << add_nums(4, 25, 25, 50, 50) << '\n';150
The above code is not a variadic template because the ellipsis in int add_nums(int count, ...) is a separate parameter rather than a part of a parameter declarator as in auto sum(const auto &... args).
%%hermes
Explain in a paragraph or two how variadic template in C++ is different from
the variadic arguments in C?↻ Session: main (ACP: b7b3b8c2-34b…)
Hermes
Where the types go. In C, the ... in int add_nums(int count, ...) is a separate parameter: everything after the last named argument lands in an anonymous bag whose types are discarded at the call boundary. The body knows neither how many arguments arrived (hence the leading count) nor what they are — each element is retrieved with va_arg(args, int) where the programmer supplies the type, and if that guess is wrong there is no diagnostic, just silently wrong behavior. Default argument promotions make even careful retrieval lossy: 'A' passed to the lecture’s function arrives as an int, and printing it yields 65, indistinguishable from having passed 65. In a C++ variadic template like auto sum(const auto&... args), by contrast, the ... attaches to a single parameter declarator inside a template, so every argument is deduced at compile time as its own entity with its exact type — I checked with a pack-expanded sizeof: sizes(1, 2.0, 'c') reports 4 8 1, all three original types preserved.
What that buys you. Because each element is a real typed expression, packs participate in ordinary compile-time checking and overload resolution: the lecture’s fold expression ((cout << args << ' '), ...) works for any type that supports <<, misuses are rejected with a normal diagnostic at compile time, and recursion can decompose head, rest.... The C mechanism is just a runtime cursor over raw storage walked through preprocessor macros with no type information anywhere — the caution cell above calls this “runtime reinterpretation.” The stakes are concrete: calling the lecture’s own add_nums(1, 1e9) and reading the value back as int printed -1530559023 on this machine with zero warnings (formally undefined behavior), while the identical computation written as a variadic template is checked by the compiler before anything runs.
Template Class¶
Recall that the python print function has the optional parameters sep and end for the string inserted between values and that appended to the last value respectively:
print(1, 2, 3, sep=", ", end=";\n")1, 2, 3;
How to take sep and end as the optional parameters in C++?
While C++ doesn’t support keyword arguments natively, you can achieve similar flexibility using the fluent interface pattern:
%%cpp
#include "utility.hpp"%%cpp
auto &myprint=printer<>::get_print();
myprint(1, 2, 3);
myprint.sep(", ")(4, 5, 6);
myprint.end(";\n")(7, 8, 9);
myprint.sep(", ").end(";\n")(1, 2, 3);1 2 3
4, 5, 6
7 8 9;
1, 2, 3;
printer<>::get_print() is defined in utility.hpp to create a printer object that uses method chaining to set sep and end. print is a functor that has a variadic template method to print a variable number of arguments.
To illustrate the idea, consider the following simplified implementation:
%%writefile private/Printer.cpp
#include <iostream>
using std::cout;
class Printer final {
const char *sep_, *end_;
Printer(const char *sep=" ", const char *end="\n")
: sep_(sep), end_(end) {}
Printer(const Printer &) = delete;
Printer(Printer &&) = delete;
Printer& operator=(const Printer&) = delete;
Printer& operator=(Printer&&) = delete;
public:
const static Printer &get_print() {
const static Printer print;
return print;
}
Printer sep(const char* s) const & { return Printer(s, end_); }
Printer end(const char* s) const & { return Printer(sep_, s); }
Printer &&sep(const char* s) && { return sep_=s, std::move(*this); }
Printer &&end(const char* s) && { return end_=s, std::move(*this); }
void operator()() const { cout << end_; }
void operator()(const auto &first, const auto &... rest) const {
cout << first;
((cout << sep_ << rest), ..., (cout << end_));
}
};
// test
#include <iostream>
int main() {
auto &myprint=Printer::get_print();
myprint.sep(", ").end(";\n")(1, 2, 3);
myprint(1, 2, 3);
return 0;
}Overwriting private/Printer.cpp
!cd private && g++ -std=c++23 Printer.cpp -o Printer && ./Printer1, 2, 3;
1 2 3
The code defines a functor class with variadic template to print a variable number of arguments:
class Printer final {
...
public:
...
void operator()() const { cout << end_; }
void operator()(const auto &first, const auto &... rest) const {
cout << first;
((cout << sep_ << rest), ..., (cout << end_));
}
};Solution to Exercise 3
If sep_ has more than one character, its last printed copy cannot be completely erased by '\b'.
Printer uses the singleton design pattern to define a unique static functor print:
get_print()uses a local static, which is efficient and thread-safe for initialization.const static Printer &get_print() { const static Printer print; return print; }
Hidden/deleted constructors/assignments prevents unnecessary copies/instantiation, which is good for performance and correctness.
... class Printer final { const char *sep_, *end_; Printer(const char *sep=" ", const char *end="\n") : sep_(sep), end_(end) {} Printer(const Printer &) = delete; Printer(Printer &&) = delete; Printer& operator=(const Printer&) = delete; Printer& operator=(Printer&&) = delete; ...The
classis also specified to befinal, which prevents inheritance, ensuring that there is no derived class that may mutateprint.
Solution to Exercise 4
The sep() and end() methods use & and && ref-qualifiers to distinguish between calls on lvalues and rvalues, enabling two different behaviors: when called on an lvalue (const &), the method returns a new Printer object with updated settings to preserve immutability; when called on an rvalue (&&), it mutates the temporary object in place and returns *this for efficient chaining without unnecessary copies.
Solution to Exercise 5
.sep(", ")resolves toPrinter sep(const char* s) const &becauseprintis an lvalue. The method returns a new instance without mutating default instanceprint, ensuring the code is thread-safe..end(";\n")resolves toPrinter &&sep(const char* s) &&becauseprint.sep(", ")is an rvalue. The method returns the rvalue withend_changed to";\n", reusing the resources of the rvalue.
Solution to Exercise 6
It fails because there is no matching function for call to Printer::sep(std::string) const. The argument of sep is const char *.
How to extend Printer to support string containers for sep and end?
One way is to create a template class:
template <class StringT = std::string> // default template argument
class Printer final {
/* original
const char *sep_, *end_;
*/
StringT sep_, end_;
/* original
Printer(const char *sep=" ", const char *end="\n")
: sep_(sep), end_(end) {}
*/
Printer(StringT sep = " ", StringT end = "\n")
: sep_(std::move(sep)), end_(std::move(end)) {}
Printer(const Printer&) = delete;
Printer(Printer&&) = delete;
Printer& operator=(const Printer&) = delete;
Printer& operator=(Printer&&) = delete;
public:
const static Printer& get_print() {
const static Printer print;
return print;
}
Printer sep(const StringT& s) const& { return Printer(s, end_); }
Printer end(const StringT& s) const& { return Printer(sep_, s); }
/* original
Printer &sep(const char* s) && { return sep_=s, *this; }
*/
template <class T>
Printer& sep(T&& s) && {
sep_ = StringT(std::forward<T>(s));
return *this;
}
/* original
Printer &end(const char* s) && { return end_=s, *this; }
*/
template <class T>
Printer& end(T&& s) && {
end_ = StringT(std::forward<T>(s));
return *this;
}
void operator()() const { cout << end_; }
void operator()(const auto &first, const auto &... rest) const {
cout << first;
((cout << sep_ << rest), ..., (cout << end_));
}
};%%cpp
template <class StringT = std::string>
class Printer final {
StringT sep_, end_;
Printer(StringT sep = " ", StringT end = "\n")
: sep_(std::move(sep)), end_(std::move(end)) {}
Printer(const Printer&) = delete;
Printer(Printer&&) = delete;
Printer& operator=(const Printer&) = delete;
Printer& operator=(Printer&&) = delete;
public:
const static Printer& get_print() {
const static Printer print;
return print;
}
Printer sep(const StringT& s) const& { return Printer(s, end_); }
Printer end(const StringT& s) const& { return Printer(sep_, s); }
template <class T>
Printer&& sep(T&& s) && {
sep_ = StringT(std::forward<T>(s));
return std::move(*this);
}
template <class T>
Printer&& end(T&& s) && {
end_ = StringT(std::forward<T>(s));
return std::move(*this);
}
void operator()() const { cout << end_; }
void operator()(const auto &first, const auto &... rest) const {
cout << first;
((cout << sep_ << rest), ..., (cout << end_));
}
};
// std::string
auto &myprint=Printer<>::get_print();
myprint.sep(string(4, '-')).end(";\n")(1, 2, 3);1----2----3;
The initialization auto &print=Printer<>::get_print(); instantiates the template class
template <class StringT = std::string> // default template argumentwith the template parameter StringT equal to the default template argument std::string.
get_print() then creates the static functor print with
...
/* original
const char *sep_, *end_;
*/
StringT sep_, end_;
/* original
Printer(const char *sep=" ", const char *end="\n")
: sep_(sep), end_(end) {}
*/
Printer(StringT sep = " ", StringT end = "\n")
: sep_(std::move(sep)), end_(std::move(end)) {}
...where sep_ and end_ have a generic type StringT that works for string containers, instead of const char *, which only works for C-string.
Solution to Exercise 7
std::move is added in the member initializer list to enable move semantics, which avoids unnecessary deep copies when initializing members from constructor parameters. In the original version, sep_(sep) and end_(end) is efficient for C-strings because only the memory addresses, not the arrays of characters, are copied.
Solution to Exercise 8
std::forward<T>(s) enables perfect forwarding of s, so sep and end work efficiently for both lvalues and rvalues without writing separate overloads:
If
Tis an lvalue reference type,std::forward<T>(s)returnssas an lvalue soStringTcan copy from it.If
Tis not an lvalue reference (i.e., the original argument was an rvalue),std::forward<T>(s)returnssas an rvalue soStringTcan move from it.
Can we also use other output streams such as std::ofstream from <fstream>?
We can add another template parameter for the output stream:
%%cpp
/* original
template <class StringT = std::string>
*/
template <class StringT = std::string, class StreamT = std::ostream>
class Printer final {
StringT sep_, end_;
StreamT* out_; // +
/* original
Printer(StringT sep = " ", StringT end = "\n")
: sep_(std::move(sep)), end_(std::move(end)) {}
*/
Printer(StringT sep = " ", StringT end = "\n", StreamT* out = &std::cout)
: sep_(std::move(sep)), end_(std::move(end)), out_(out) {}
Printer(const Printer&) = delete;
Printer(Printer&&) = delete;
Printer& operator=(const Printer&) = delete;
Printer& operator=(Printer&&) = delete;
public:
const static Printer& get_print() {
const static Printer print;
return print;
}
template <class T>
Printer&& sep(T&& s) && {
sep_ = StringT(std::forward<T>(s));
return std::move(*this);
}
template <class T>
Printer&& end(T&& s) && {
end_ = StringT(std::forward<T>(s));
return std::move(*this);
}
/*
### BEGIN SOLUTION
*/
/**
* @note Unlike StringT, StreamT is stored by pointer rather than value.
* Only lvalue streams are accepted to prevent dangling pointers
* caused by temporary streams.
*/
Printer&& stream(StreamT& s) && { // +
out_ = &s; // +
return std::move(*this); // +
} // +
/* original
Printer sep(const StringT& s) const& { return Printer(s, end_); }
*/
Printer sep(const StringT& s) const& { return Printer(s, end_, out_); }
/* original
Printer end(const StringT& s) const& { return Printer(sep_, s); }
*/
Printer end(const StringT& s) const& { return Printer(sep_, s, out_); }
Printer stream(StreamT& s) const& { return Printer(sep_, end_, &s); } // +
/* original
void operator()() const { cout << end_; }
*/
void operator()() const { *out_ << end_; }
/* original
void operator()(const auto &first, const auto &... rest) const {
cout << first;
((cout << sep_ << rest), ..., (cout << end_));
}
*/
void operator()(const auto &first, const auto &... rest) const {
*out_ << first;
((*out_ << sep_ << rest), ..., (*out_ << end_));
}
/*
### END SOLUTION
*/
};
// std::string
auto &myprint=Printer<>::get_print();
myprint.sep(string(4, '-')).end(";\n")(1, 2, 3);
// Use a file stream
std::ofstream file("private/output.txt");
myprint.stream(file).sep(" -> ").end("\n")("File", "Output");
file.close();1----2----3;
!cat private/output.txt
# File -> OutputFile -> Output
Solution to Exercise 10
StringTsuch asstd::stringis often copyable. Storing them by value ensures they are always valid for the lifetime of thePrinterobject, avoids dangling pointers, and simplifies memory management.In contrast, streams like
std::ostreamare often non-copyable and resource-bound, e.g., tied tostd::coutor a file handle. Attempting to store them by value would fail or would break resource semantics. Instead, a pointer can be stored to refer to an existing stream without taking ownership.