【发布时间】:2020-07-31 13:23:27
【问题描述】:
我尝试在 C++ 中创建一个编译时简单键值映射。我正在使用/std:c++11 进行编译。
(内嵌代码使用IAR编译器,目前只支持cpp++11)
我对元编程有所了解。
如果找不到键,我不希望我的地图有默认值, 喜欢这篇文章:How to build a compile-time key/value store?
如果在我的代码中我试图获取一个未存储在映射中的值,我想得到编译器错误。
这是我所做的:
#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>
{
template<int k_input>
struct get
{
static const int val = (k_input == kv::k) ? kv::v;
};
};
// ----------------------------- Main -----------------------------
typedef CompileTimeMap<KeyValue<10, 20>, KeyValue<11, 21>, KeyValue<23, 7>> mymap;
int main()
{
// This calles should be ok !! :)
std::cout << mymap::get<10>::val << std::endl;
std::cout << mymap::get<11>::val << std::endl;
std::cout << mymap::get<23>::val << std::endl;
// This line should resolve a compile error !! (there is no key of 33)
std::cout << mymap::get<33>::val << std::endl;
}
我收到以下错误:error C2131: expression did not evaluate to a constant。
我怎样才能做到这一点?非常感谢:)
【问题讨论】:
-
consts 必须是constexpr -
这不起作用的原因有很多:1)在constexpr中禁止内存分配,因为当没有分配器运行时您无法分配内存。这意味着没有字符串、向量或任何容器映射。将 int 映射到 int 可能没问题,但随后您将面临另一个问题:2) C++11 的 constexpr 非常有限 并且只允许非常简单的表达式而没有任何局部变量。您至少需要 C++17 才能获得更好的元编程体验
标签: c++ templates metaprogramming key-value template-meta-programming