在编译期间逐步构建和使用地图

问题描述

我想在编译期间建立一个使用类型的映射,并验证所有条目是否一致。

用法示例是一组配置设置,这些设置是根据代码中的用法定义的。

template <typename T>
constexpr void add_to_map(std::string key,T) {
  // Check that key isn't saved in the map with a different type. Compilation error if check fails.
  // Add new entry to map
}

// Exampel usage
template <typename T>
void set_setting(std::string key,T value) {
  add_to_map(key,value); // Check that this key/type combination is unique

  // Add/set the value of key in some container,e.g. std::map
}

template <typename T>
T get_setting(std::string key) {
  add_to_map(key,T{}); // Check that this key/type combination is unique

 // Return the value for key
}

int main() {
  set_setting("pi",3.14);  // OK
  set_setting("answer",42); // OK
  get_setting<int>("answer"); // OK
  set_setting("pi",3.0);  // OK

  set_setting("answer",42.0); // Error,wrong type
  get_setting<bool>("pi"); // Error wrong type
}

问题是如何实现add_to_map()。请注意,这并不是建立设置图。它正在建立设置类型的映射。该映射仅在编译时使用。

显然必须对密钥进行硬编码。

我认为这是无法完成的事情。但我很高兴看到部分解决方案。最好使用C ++ 17,但是使用C ++ 20甚至标准提案也很有趣。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)