如何在 C++ 中编写整数和平凡类型之间的双向映射?

Ale*_*son 3 c++ templates types template-meta-programming

我想在int和 C++ 平凡类型之间编写一个双射,例如doubleor float

双射在编译时是已知的。

我想像这样使用它(大写表示宏):

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;
}
Run Code Online (Sandbox Code Playgroud)

Woo*_*ord 9

INIT如果你想避免宏,你可以扩展,但它确实很好地清理了样板:

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;
}
Run Code Online (Sandbox Code Playgroud)