Incrementally build and use a map during compile time

Viewed 98

I would like to build a map of used types during compile time and verify that all entries are consistent.

An example usage would be a set of configuration settings that are are defined from their usage in the code.

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
}

The question is how to implement add_to_map(). Note that this is not building the map of settings. It's building a map of the settings types. This map is only used during compile time.

Keys would obviously have to be hard coded.

I assume this this is something that can't be done. But I would be happy to see a partial solution. C++17 would be best, but usage of C++20 or even standard proposals would also be of interest.

0 Answers
Related