Last week I was playing with C++, trying to rewrite again the “usual” n-dimension Vector/Point/Matrix library. This is an experiment (someone would call it a kata) I did several times mostly as a test bench for language/compiler features I’m learning (e.g. lazy evaluation with expression templates, SIMD intrinsics, etc…).

Objects of this library usually represent these entities:

  • Points – they represent points in the euclidean space
  • Vectors – you can see them as directions, distance between points in space
  • Matrices – transformations

I like differentiating points from vectors because you should treat them differently when applying transformations (points are translated, while vectors are not) and allows you to provide compile-time errors when suspect operations are performed (e.g. adding two points, which is meaningless).

Also, my object are specialised for base type (e.g. float, double) and dimensionality (usually I implement 2D and 3D cases, but sometimes arbitrary size can be an interesting case-study).

So I typically end up with several objects, with similar properties and functions, and much of the code replicated several times.

This time I wanted to adopt a functional style, and to concentrate on the code maintainability, writing the smallest number of lines as possible. After a few steps of refactoring, I ended up with most of the essential features concentrated a single, recursively defined object: a list. This was unexpected, even to me, because I was expecting something more similar to array, but that object definitely had all the feature I wanted.

I decided to suspend my main goal, and concentrate on this interesting object, whose structure is:

template <typename T, int N> struct VecImpl { 
    T first; 
    VecImpl<T, N - 1> rest;

template <typename T> struct VecImpl<T, 1> {
    T first;
template <typename T> struct VecImpl<T, 0> {

In the next post I’ll show how to construct and access this struct.

Edit 2015/03/02 Added a specialization for 1-element.

Leave a Reply