Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: inheritance problem
    primarykey
    data
    text
    <p>It's quite hard to explain what I'm trying to do, I'll try: Imagine a base <code>class A</code> which contains some variables, and a set of classes deriving from <code>A</code> which all implement some method <code>bool test()</code> that operates on the variables inherited from <code>A</code>.</p> <pre><code>class A { protected: int somevar; // ... }; class B : public A { public: bool test() { return (somevar == 42); } }; class C : public A { public: bool test() { return (somevar &gt; 23); } }; // ... more classes deriving from A </code></pre> <p>Now I have an instance of <code>class A</code> and I have set the value of <code>somevar</code>.</p> <pre><code>int main(int, char* []) { A a; a.somevar = 42; </code></pre> <p>Now, I need some kind of container that allows me to iterate over the elements <code>i</code> of this container, calling <code>i::test()</code> in the context of <code>a</code>... that is:</p> <pre><code> std::vector&lt;...&gt; vec; // push B and C into vec, this is pseudo-code vec.push_back(&amp;B); vec.push_back(&amp;C); bool ret = true; for(i = vec.begin(); i != vec.end(); ++i) { // call B::test(), C::test(), setting *this to a ret &amp;= ( a .* (&amp;(*i)::test) )(); } return ret; } </code></pre> <p>How can I do this? I've tried two methods:</p> <ol> <li>forcing a cast from B::* to A::*, adapting a pointer to call a method of a type on an object of a different type (works, but seems to be bad);</li> <li>using std::bind + the solution above, ugly hack;</li> <li>changing the signature of <code>bool test()</code> so that it takes an argument of type <code>const A&amp;</code> instead of inheriting from A, I don't really like this solution because somevar must be public.</li> </ol> <p><strong>EDIT:</strong></p> <p>Solution (1) is:</p> <pre><code>typedef bool (A::*)() mptr; std::vector&lt;mptr&gt; vec; vec.push_back(static_cast&lt;mptr&gt;(&amp;T::test)); std::vector&lt;mptr&gt;::iterator i; for(i = vec.begin(); i != vec.end(); ++i) { (a .* (*i))(); } </code></pre> <p>I'm not sure the static cast is safe.</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