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

后端 未结 5 1997
灰色年华
灰色年华 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 11:38

    In C++11:

    template 
    struct kv
    {
        static const int k = kk, v = vv;
    };
    
    template 
    struct ct_map;
    
    template 
    struct ct_map
    {
        template
        struct get
        {
            static const int val = dflt;
        };
    };
    
    template
    struct ct_map, rest...>
    {
        template
        struct get
        {
            static const int val =
                (kk == k) ?
                v :
                ct_map::template get::val;
        };
    };
    
    typedef ct_map<42, kv<10, 20>, kv<11, 21>, kv<23, 7>> mymap;
    
    #include 
    int main()
    {
        std::cout << mymap::get<10>::val << std::endl;
        std::cout << mymap::get<11>::val << std::endl;
        std::cout << mymap::get<23>::val << std::endl;
        std::cout << mymap::get<33>::val << std::endl;
    }
    

提交回复
热议问题