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

后端 未结 5 1987
灰色年华
灰色年华 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条回答
  •  -上瘾入骨i
    2020-12-08 11:41

    Something like this would work:

    template
    struct StaticMap {
      static const int Value = 0;
    };
    
    template<>
    struct StaticMap<1> {
      static const int Value = 3;
    };
    
    int main()
    {
      cout << StaticMap<0>::Value << ", " 
           << StaticMap<1>::Value << ", "
           << StaticMap<2>::Value << endl;
    }
    

    0 is the default value, and a key of 1 gives a value of 3. Add additional specializations as needed.

    Is this the general idea of what you're looking for? It's not the interface you requested, although preprocessor macros (such as Boost.Preprocessor) could streamline and simplify setting it up.

提交回复
热议问题