Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>1) I would use seperate static members for each type to hold the allowed attributes for each type.<br> 2) Move the static members into functions, which is safer, and possibly avoids checking to see if it's initialized all the time (depending on how good your compiler is and other details)<br> 3) Don't use <code>const char*</code> except for very specific things. If you don't know what those things are, always use <code>std::string</code>. In this case, we <em>have</em> to use <code>std::string</code>.<br> 4) I changed <code>allowedAttrs</code> from a vector to a <code>set</code>, which might be faster for large numbers of attributes, and slower for smaller numbers, maybe.</p> <p>Here's the base:</p> <pre><code>class DataObj { const std::set&lt;std::string&gt;&amp; get_allowed_data_attributes() static { static std::set&lt;std::string&gt; allowedAttrs = {"name"}; return allowedAttrs; } std::map &lt;std::string, std::string&gt; attrs; public: DataObj(){ } void set_attribute(std::string key, std::string value) { auto it = get_allowed_data_attributes().find(key); if (it == get_allowed_data_attributes().end()) throw bad_key_exception(key); attrs.insert(std::make_pair(std::move(key), std::move(value))); } const std::string&amp; get_attribute(const std::string&amp; key) const { auto it = attrs().find(key); if (it == attrs().end()) throw bad_key_exception(key); return it-&gt;second; } }; </code></pre> <p>Here's the derived:</p> <pre><code>class Layer : public DataObj { const std::set&lt;std::string&gt;&amp; get_allowed_data_attributes() static { static std::set&lt;std::string&gt; allowedAttrs = {"locked"}; return allowedAttrs; } public: DataObj(){ } void set_attribute(std::string key, std::string value) { auto it = get_allowed_data_attributes().find(key); if (it == get_allowed_data_attributes().end()) DataObj::set_attribute(std::move(key), std::move(value)); else attrs.insert(std::make_pair(std::move(key), std::move(value))); } const std::string&amp; get_attribute(const std::string&amp; key) const { auto it = attrs().find(key); if (it == attrs().end()) return DataObj::get_attribute(key); else return it-&gt;second; } }; </code></pre> <p>Note that if you give it an invalid key, it throws a <code>bad_key_exception</code>, which you will have to add. Be sure it inherits from <code>std::runtime_error</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload