Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to work around 'const' definition in library
    primarykey
    data
    text
    <p>I'm using a library that defines some data type classes usually implemented as tight wrappers around a std::vector&lt;>. The type hierarchy is several layers deep, mostly only adding elaborated constructors.</p> <p>My problem: the base class defines its std::vector as private (which is fine), but only adds an accessor method as const. The derived class doesn't even have access to it. The library looks like this (shorted for clarity):</p> <pre><code>template &lt;class T&gt; class BaseList { public: BaseList (const T data0) : data_ (1) { data_[0] = data0; } const T &amp; operator[] (const size_t nr) const { // does out off bounds check here return data_[nr]; } private: std::vector&lt;T&gt; data_; } class FancyClass : public BaseList&lt;SomeEnumType&gt; { public: FancyClass (const SomeOtherEnumType data0) : BaseList&lt;SomeEnumType&gt; ( static_cast&lt;SomeEnumType&gt; (data)) {} } </code></pre> <p>Now as I see it, the const definition is completely bogus. No internal method relies on the vector really being constant, neither do I in my external code.</p> <p>What I like to do is simply this:</p> <pre><code>strukt MyType { FancyClass myData; bool otherData; } int main() { MyType storage = {FancyClass(0), false}; storage.myData[0] = 5; } </code></pre> <p>Which of course doesn't work because of the const-ness. ("assignment of read-only location")</p> <p>With the responsibility completely on my side: is there some const_cast magic I could do to make this structure writable? The only other possibility I know would be to completely replicate the type hierarchy in my code, but this would still leave me with either a lot of casts or a toFancyClass() function to call whenever I interface library code.</p> <p>Any Ideas? Thanks!</p> <p>(Please don't comment on the code quality of the library. If I could change that, I wouldn't be asking this question ...)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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