Search code examples
c++stdmapinitializer-list

How to initialize a custom container with a multi-dimensional initializer list?


I'm currently working on a custom wrapper for the std::map type with additional methods like ContainsValue(). But since I try to make it as compatible with std::map as possible, I'd like to know if it's possible to initialize it with a "multi-dimensional initializer list".

My custom map type is defined like this:

template <typename TKey, typename TValue>
class CustomMap {
private:
  std::map<TKey, TValue> mapContent;

public:
  // Some interaction methods here

  void operator=(/* initialization type here */) {
    /* initialization here */
  }
}

And I'm talking about an initializer list like this:

CustomMap<uint64_t, std::string> test = {
  { 0xFF, "MaxByte" },
  { 0xFFFF, "MaxWord" },
  { 0xFFFFFFFF, "MaxDWord" },
  { 0xFFFFFFFFFFFFFFFF, "MaxQWord" }
};

Notice that there's no casting of any type in the initialization. It's all happening automatically; just as with the original std::map type.


Solution

  • Sure, make a constructor taking std::initializer_list<value_type> like std::map has: https://en.cppreference.com/w/cpp/container/map/map

    Or forward all constructors: Forwarding all constructors in C++0x