How can I code a bidirectional map between an integer and a trivial type in C++?

Viewed 136

I would like to code a bijection between int and C++ trivial type such as double or float.

The bijection is known at compile time.

I would like to use it like this (caps denotes a macro):

INIT(42,float)
INIT(-17,double)

#include <type_traits>

int main() {
    const int a = TYPE_TO_INT(float);
    static_assert(a==42);
    INT_TO_TYPE(-17) pi;
    static_assert(std::is_same<double,decltype(pi)>::value);
    return 0;
}
1 Answers

You can expand INIT if you want to avoid macros but it does nicely clean up the boilerplate:

template <typename T> struct TypeToInt {};
template <int T> struct IntToType {};

#define INIT(i, t) \
    template <> struct TypeToInt<t> { constexpr static int value = i; }; \
    template <> struct IntToType<i> { using type = t; };

INIT(42,float);
INIT(-17,double);

int main() {
    const int a = TypeToInt<float>::value;
    static_assert(a==42);
    IntToType<-17>::type pi;
    static_assert(std::is_same<double,decltype(pi)>::value);
    return 0;
}
Related