A C++ template allows to write code that works for any data type without rewriting it for each type.
The below function can use different input types (int, double, char, …).
// Template for max function
template <typename T> T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
cout << "Max of 3 and 7 is: " << myMax<int>(3, 7) << endl;
cout << "Max of 3.5 and 7.5 is :" << myMax<double>(3.5, 7.5) << endl;
cout << "Max of 'g' and 'e' is: " << myMax<char>('g', 'e') << endl;
return 0;
}
In the below, the function (used to update the order book) can use any comparator. It’s useful because the arrays containing the ask / bid prices are typically sorted in a different order (hence different comparator).
// Template for order book update
class OrderBook {
private:
std::map<double, double> asks;
std::map<double, double, std::greater<>> bids;
template<typename Comparator>
void update(std::map<double, double, Comparator>& bids_or_asks,
const nlohmann::json& updates) {
for (auto& level : updates) {
double price = std::stod(level[0].get<std::string>());
double qty = std::stod(level[1].get<std::string>());
if (qty == 0) bids_or_asks.erase(price);
else bids_or_asks[price] = qty; // for asks: this puts
the best (lowest) price in first
}
}