我有一个问题,我需要在编译时将一个整数映射到另一个整数.基本上,我需要编译时相当于std::map<int,int>
.如果在地图中找不到某个键,我想返回一个默认值.
我想使用的界面:
template<unsigned int default_value,
unsigned int key0, unsigned int value0,
unsigned int key1, unsigned int value1,
...>
struct static_map
{
...
};
template<unsigned int key, typename StaticMap>
struct lookup
{
static unsigned int value = ...
};
Run Code Online (Sandbox Code Playgroud)
lookup
返回与相关联的值key
中StaticMap
.如果key
未找到,则default_value
返回.
在一般情况下,键/值对的数量将被限制一些> 2.什么是打造最好的方式来界定static_map
和lookup
?
我还要提一下,我仅限于使用C++ 03语言结构,因此没有C++ 11,也没有外部库依赖.
这是我得到的解决方案,受到nm和DyP的答案的启发:
#include <iostream>
template<unsigned int k, unsigned int v>
struct key_value
{
static const unsigned int key = k;
static const …
Run Code Online (Sandbox Code Playgroud)