title: String type with max length
body: <p>I need to implement a C++11 or C++14 type STRING that acts just like <code>std:string</code>, but has the following additional constraints/features:</p>
  
  <ol>
  <li>WIDTH parameter specified during declaration. STRING will
  throw exception if its length is greater than WIDTH</li>
  <li>Optional FIXED parameter specified during declaration. STRING will throw exception if its length is not equal to WIDTH</li>
  </ol>
  
  <p>In all other respects, STRING is supposed to behave just like <code>std::string</code> and expose the same member functions as <code>std:string</code> (such as <code>.append()</code> etc..).</p>
  
  <p>My first instinct was to use a template class <code>STRING</code> that holds a <code>std::string</code>, like so:</p>
  
  <pre><code>template&lt;int WIDTH= 0, bool FIXED = false&gt;
  class STRING {
      static_assert(WIDTH &gt;= 0, "WIDTH of STRING cannot be negative.");
  public:
      STRING() : value{} { }
  
      STRING(const std::string &amp;s) { if (is_valid(s)) value = s; }
  
      STRING(const char c[]) { if (is_valid(c)) value = c; }
  
      STRING&amp; operator=(const std::string&amp; s){ if (is_valid(s)) value = s;}
      operator std::string() const { return value; }
  
  
      std::string value;
  
  private:
      bool is_valid(const std::string &amp;s) {
          if (WIDTH &amp;&amp; s.length() &gt; WIDTH)
              throw std::length_error{"STRING assignment failed. STRING too long."};
          if (FIXED &amp;&amp; s.length() != WIDTH)
              throw std::length_error{"STRING assignment failed. STRING has wrong length."};
          return true;
      }
  };
  </code></pre>
  
  <p>However, the above <code>STRING</code> template class does not expose <code>std::string</code> member functions and I do not want to re-implement the entire <code>std::basic_char</code> function set, so I think my approach is fundamentally wrong. I suspect somehow extending <code>std::string</code> might be better, but it seems a little scary to "mess" with the standard library types.</p>
  
  <p>I am not sure what the best approach would be here and pointers in the right direction would be more than welcome.</p>