Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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
  1. * is an unpacking operator in Python. In *args, args is 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
  1. sep=' ' and end='\n' are optional keyword-only parameters which are specified as follows:

print(1, 2 ,3, sep=", ", end=";\n")
1, 2, 3;
  1. file allows 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.txt
Hello, 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 && ./pack
3

In the above definition

  • auto... pack is a named constant template parameter

    type ... 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 pack args.

However, many types are not structural types, and we often want a function to take mutable arguments. For instance:

  1. cout << foo<"def">() << '\n';

    fails because "def" is not a valid template argument for type const char*. String literals cannot be used in this context.

  1. const int a=rand();
    cout << foo<a>() << '\n';  

    fails because a is 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?
Loading...
🌿 Fork/new: main (will create on click)

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 && ./pack
4

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++.
Loading...
↻ Session: main (ACP: b7b3b8c2-34b…)

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 && ./print
1 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 expansion

    pattern ...

    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 call print(1, 2.0, 'c', "def");, the recursive call print(rest...) is expanded to

    print(
        2.0, 'c', "def"  // rest...
    );
  • In the function parameter pack const Ts &... rest, pack expansion is also applied to const Ts &... to expand the template parameter pack class... Ts.
    E.g., for the call print(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?
Loading...
↻ Session: main (ACP: b7b3b8c2-34b…)

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 && ./Printer
1, 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 class is also specified to be final, which prevents inheritance, ensuring that there is no derived class that may mutate print.

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 to Printer sep(const char* s) const & because print is an lvalue. The method returns a new instance without mutating default instance print, ensuring the code is thread-safe.

  • .end(";\n") resolves to Printer &&sep(const char* s) && because print.sep(", ") is an rvalue. The method returns the rvalue with end_ 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 argument

with 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 T is an lvalue reference type, std::forward<T>(s) returns s as an lvalue so StringT can copy from it.

  • If T is not an lvalue reference (i.e., the original argument was an rvalue), std::forward<T>(s) returns s as an rvalue so StringT can 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 -> Output
File -> Output
Solution to Exercise 10
  1. StringT such as std::string is often copyable. Storing them by value ensures they are always valid for the lifetime of the Printer object, avoids dangling pointers, and simplifies memory management.

  2. In contrast, streams like std::ostream are often non-copyable and resource-bound, e.g., tied to std::cout or 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.