我尝试在 C++ 中创建一个编译时简单的键值映射。我正在编译/std:c++11. (使用IAR编译器进行嵌入代码,目前仅支持cpp++11)
我了解了一些关于元编程的知识。
如果找不到键,我不希望我的映射具有默认值,例如这篇文章:如何构建编译时键/值存储?
如果在我的代码中我试图获取未存储在映射中的值,我想得到编译器错误。
这是我所做的:
#include <iostream>
template <int kk, int vv>
struct KeyValue
{
static const int k = kk, v = vv;
};
// Declaration
template <typename kv, typename...>
struct CompileTimeMap;
// Recursive Definition
template<typename kv, typename... rest>
struct CompileTimeMap<kv, rest...>
{
template<int k_input>
struct get
{
static const int val = (k_input == kv::k) ? kv::v : CompileTimeMap<rest...>::get<k_input>::val;
};
};
// Base Definition
template <typename kv>
struct CompileTimeMap<kv> …Run Code Online (Sandbox Code Playgroud) c++ templates metaprogramming key-value template-meta-programming