Skip to content

Instantly share code, notes, and snippets.

@RMDarth
RMDarth / ClassMethodTester.cpp
Last active September 23, 2020 20:31
Visit template class and invoke its method by generic lambda, with default function call when method doesn't exist
// I had an issue when there are a lot of classes (or structures), which are not related to each other,
// yet most of them have fields or methods with the same name/signature - for example getName(), or getOperationCode().
// I wanted a simple method, like GetParam(my_object, GetName(), "NoName"), which will return name if the provided method
// is present, and return default value if it's not. Codebase is in C++14.
// To achieve this, we can use 2 template methods - one, which will try to get given param, and second with default behaviour.
// First method could use generic lambda as a parameter to access the param. But SFINAE doesn't work with such lambda, so
// lambda, too, must use additional enabler for itself, so it won't be instantiated for class which doesn't have given param.
//
// Here is simplified solution for the described issue. To simplify creating the lambda with all the checks, I've added a
// macro "invoke", which will only need the object, default value and expression to access the paramet
@RMDarth
RMDarth / StructureFieldBitSize.cpp
Last active February 2, 2024 02:47
Compile-time size of the field in bit field struct (with C++11 restrictions)
// I've needed a constexpr way to get a size of the bit fields in struct (i.e. number of bits).
// Also, I needed it to work in Visual Studio 2015 (SP3), which is not yet fully support C++14,
// so constexpr functions could only use a single return statement and (almost) nothing more.
// After some time I've come up with this solution. It should work with any C++11 compiler.
// It has some limitations (it only works with unsigned fields).
// P.S.: With C++17 it could be done easier by using constexpr lambda expressions in macro.
#include <iostream>
#include <array>
// Helper constexpr functions