How to build a compile-time key/value store?

后端 未结 5 1990
灰色年华
灰色年华 2020-12-08 11:06

I have a problem where I need to map an integer at compile time to another integer. Basically, I need the compile-time equivalent of std::map. If

5条回答
  •  轮回少年
    2020-12-08 12:02

    You can use template specialization

    template 
    struct Map;
    
    template 
    struct Map { static const int value = -1; }; // not exists node
    
    template <> struct Map< 'A' > { static const int value = 1; }; // 'A' -> 1
    template <> struct Map< 'B' > { static const int value = 2; }; // 'B' -> 2
    // ....
    
    int lookup = Map<'B'>::value; // = 2
    

    You can avail yourself of some macros to simplify the definition of content.

提交回复
热议问题