Programs & Examples
Static and Friend Members · Study material
Per-type ID generator with a CRTP base
Because each instantiation of a class template has its own static members, WithId<Invoice> and WithId<Customer> keep independent counters.
#include <iostream>
#include <string>
template <typename Derived>
class WithId { // CRTP: each derived class gets its own counter
static inline int next_ = 1;
int id_;
protected:
WithId() : id_(next_++) {}
public:
int id() const { return id_; }
static int issued() { return next_ - 1; }
};
class Invoice : public WithId<Invoice> {};
class Customer : public WithId<Customer> {};
int main() {
Invoice i1, i2, i3;
Customer c1, c2;
std::cout << "INV-" << i3.id() << " CUS-" << c2.id() << ' '
<< Invoice::issued() << ' ' << Customer::issued() << '\n';
return 0;
}
INV-3 CUS-2 3 2
A configuration singleton
The Config class in the introduction is created lazily on first use, can never be copied, and every call to Config::instance() returns the same object.
Money with symmetric friend operators and stream I/O
The Money example shows why non-member friends are used for operators: 50 + price compiles because both operands may be converted, and >>/<< read and print the private amount.