相关疑难解决方法(0)

如何构建编译时键/值存储?

我有一个问题,我需要在编译时将一个整数映射到另一个整数.基本上,我需要编译时相当于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返回与相关联的值keyStaticMap.如果key未找到,则default_value返回.

在一般情况下,键/值对的数量将被限制一些> 2.什么是打造最好的方式来界定static_maplookup

我还要提一下,我仅限于使用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)

c++ template-meta-programming

13
推荐指数
3
解决办法
9825
查看次数

标签 统计

c++ ×1

template-meta-programming ×1