Category Archives: Utilities

(Almost) Generic Comparison Operator For Structs

Introduction

A simple struct is easy to write. The compiler generates default constructors for us (unless we disturb it). It is readily to be used in vectors and lists, the world is nice.

And then you want to use you shiny new struct as a key in a map. Hmmpf. Need to write a less operator…

OK, so lets assume this is our struct:

Here’s a handcrafted less operator:

This is annoying to write. It is prone to errors while writing it the first time and also when time comes for maintenance (e.g lets add a language and swap title and author).

Macros come to mind, but many people frown on them.

Pointer-to-data-member to the rescue

Pointers to data members look quite weird if you aren’t used to them. But they allow us to specify access to data members of a struct via the pointer-to-member-access operators.

In combination with variadic templates we can write a generic less function that compares structs by data members with a given precedence.

m and rest sure look a bit crazy, being mixed with T, but they get the job done. They are used to iterate through a given order of data members.

And this is how we can use it to compare Talk objects:

This is nice and simple again, suiting a simple struct 🙂