2

I am using a std::map to map some unsigned char machine values into human readable string types, e.g.:

std::map<unsigned char, std::string> DEVICE_TYPES = {
    { 0x00, "Validator" },
    { 0x03, "SMART Hopper" },
    { 0x06, "SMART Payout" },
    { 0x07, "NV11" },
};

I'd like to modify this so that if the key passed is not present, the map will return "Unknown". I want the caller interface to stay the same (i.e. they just retrieve their string from the map using the [] operator). What's the best way to do this? I have C++11 on Windows 7 available.

2
  • 3
    Create a wrapper and implement the [] operator. Commented Jan 25, 2017 at 18:27
  • Good suggestion. I'm not sure what the constructor would look like for using a list initializer like I have in the example however. Any ideas on that? Commented Jan 25, 2017 at 18:31

1 Answer 1

7

You might create some wrapper with operator[] overloaded to provide the required behaviour:

class Wrapper {
public:
    using MapType = std::map<unsigned char, std::string>;

    Wrapper(std::initializer_list<MapType::value_type> init_list)
        : device_types(init_list)
    {}

    const std::string operator[](MapType::key_type key) const {
        const auto it = device_types.find(key);
        return (it == std::cend(device_types)) ? "Unknown" : it->second;
    }

private:
    const MapType device_types;
};

wandbox example

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, looks ideal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.