Note that there are some explanatory texts on larger screens.

plurals
  1. POTemplate Friend for Superclass
    primarykey
    data
    text
    <p>I have a non-templatized class (Par_list_elem), and I would like to give access to its internals to the class Par_list (to build an intrusive list).</p> <p>The catch: I need Par_list_elem and <strong>all of its subclasses</strong> to be accessible to Par_list. In detail, the only fields that need to be accessible are _next and _prev; explicitly limiting to those fields would be nice, but isn't required.</p> <p>I've made a few preliminary attempts at doing this, the latest of which is below:</p> <pre><code> template &lt;class T&gt; class Par_list { public: Par_list() : _head(0) {} ~Par_list(); //Insert element into list bool insert(T elem); //Remove element identified by iterator void erase(iterator itr); private: T* _head; }; class Par_list_elem { public: Par_list_elem() : _next(0), _prev(0) {} //Get next element in list Par_list_elem* next() { return _next; } private: Par_list_elem* _next; Par_list_elem* _prev; template &lt;typename&gt; friend class Par_list; }; template &lt;class T&gt; void Par_list&lt;T&gt;::erase(Par_list&lt;T&gt;::iterator itr) { T* e = *itr; T* p; if ((p = e-&gt;_prev) != 0) p-&gt;_next = e-&gt;_next; else _head = e-&gt;_next; if ((e-&gt;_next) != 0) (e-&gt;_next)-&gt;_prev = p; delete e; } template &lt;class T&gt; bool Par_list&lt;T&gt;::insert(T* nelem) { T* curr = _head; if (curr != 0) { while (curr-&gt;_next != 0) curr = curr-&gt;next(); curr-&gt;_next = nelem; } else _head = nelem; nelem-&gt;_prev = curr; nelem-&gt;_next = 0; return true; } </code></pre> <p>test.cpp</p> <pre><code>#include "parsnip_list_back.h" class elem : parsnip::Par_list_elem { int _elem; }; int main (int argc, char** argv) { parsnip::Par_list&lt;elem&gt; plist; return 0; } </code></pre> <p>Some information seems to be available here: <a href="https://stackoverflow.com/questions/3292795/template-friend">Template friend</a> But the goal is different in enough detail that I'm stuck.</p> <p>Thanks!</p> <p>--------UPDATE---------</p> <p>The following sort of error occurs for each instance of an access of a private member of Par_list_elem. I'm compiling on gcc 4.4. </p> <pre><code>parsnip_list_back.h:66: error: ‘parsnip::Par_list_elem* parsnip::Par_list_elem::_prev’ is private parsnip_list_back.h:124: error: within this context </code></pre> <p>So, with the current implementation, even the superclass isn't giving up its privates.</p>
    singulars
    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