getcracked
Blog / Coding

C++ Templates for HFT

Coding

In web development, we love interfaces and virtual functions. They make code flexible. In HFT, virtual is a dirty word.

The Cost of Runtime Polymorphism

When you call a virtual function, the CPU has to:
1. Look up the vtable pointer.
2. Retrieve the function address.
3. Jump to that address.

This prevents inlining. If a function is 3 instructions long, the overhead of the jump is bigger than the work itself. In HFT, we want the compiler to inline everything into a massive flat stream of instructions.

Curiously Recurring Template Pattern (CRTP)

This is how we achieve polymorphism at compile time.

template <typename Derived>
class OrderExecution {
public:
    void execute(Order o) {
        // Interface-like call, but resolved at compile time!
        static_cast<Derived*>(this)->sendToExchange(o);
    }
};

class NasdaqHandler : public OrderExecution<NasdaqHandler> {
public:
    void sendToExchange(Order o) {
        // Nasdaq specific code
    }
};

Here, the compiler generates a specialized class for NasdaqHandler. The execute function knows exactly which sendToExchange to call. No pointers. No lookups. Just speed.

Template Metaprogramming in C++20

With concepts and constexpr, template code is much more readable now. We use it to unroll loops, compute lookup tables at compile time, and generate specialized parsers for exchange protocols (FIX/SBE).