Reflection in C++14

Simon Ninon
14 min readDec 10, 2020

A stupid challenge

A few months ago, I was playing around with C++ by trying to build an MVC web framework similar to Ruby on Rails. The project itself didn't have an end goal, besides experimenting with a few things, but it brought interesting challenges.

One of the challenges was routes configuration. One of the most important mechanisms of an MVC web framework is to configure some routes (API endpoints) that the client can request. Each route is associated with a specific action of a controller.

For example, we can have a /articles route that is linked to the index action of the articles controller. When the client requests this path, articles_controller::index is called and returns a list of the articles.

For this project, one challenge I set to myself was to find a way to make the configuration language-agnostic: would it be possible to configure this from a JSON file with a syntax similar to Ruby on Rails.

This idea directly leads us to the topic of this article: how to convert strings like articles#index to the call ArticlesController(...).index(...). The answer is Reflection.

Reflection Introduction

What is Reflection?

Reflection is, in some languages, a language mechanism that gives us the ability to retrieve information from a type or a method, dynamically, at runtime.

Additionally, reflection can let us instantiate an object from a string containing the class name, or call a method from a string containing its name.

For example, in Ruby on Rails, we can do "SomeClass" "some_method" and it will call SomeClass::some_method at runtime.

Native Reflection in C++

There is no reflection engine natively in C++, even in the latest version.

Simon Ninon

Senior Software Engineer at Snowflake. Living in Seattle.