Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This works, though is somewhat nasty:</p> <pre><code>#include &lt;string&gt; #include &lt;iostream&gt; class A { public: std::string msg; A(std::string s) { msg = s;} void filter() { std::cout &lt;&lt; "Message A = " &lt;&lt; msg &lt;&lt; std::endl;} }; class B { public: std::string msg; B(std::string s) { msg = s;} void filter() { std::cout &lt;&lt; "The B message: " &lt;&lt; msg &lt;&lt; std::endl;} }; // ------------- class Base { public: virtual void filter() = 0; virtual ~Base() {} }; template&lt;class C&gt; class Wrapper: public Base { public: Wrapper( C * impl ): m_impl(impl) { } ~Wrapper() { delete m_impl; } virtual void filter() { m_impl-&gt;filter(); } private: C * m_impl; }; // ------------- int main() { Base * f = NULL; int type = 1; switch (type) { case 1: f = new Wrapper&lt;A&gt;(new A("hi from A")); break; case 2: f = new Wrapper&lt;B&gt;(new B("hello from B")); break; } f-&gt;filter(); delete f; } </code></pre> <hr> <p>And the C++11, exception-safe variant with perfect forwarding of the constructors. Just <code>Wrapper</code> and <code>main()</code> are different from above, here they are:</p> <pre><code>template&lt;typename T&gt; class Wrapper : public Base { public: template&lt;typename... Args&gt; Wrapper(Args&amp;&amp;... args) : m_impl(std::forward&lt;Args&gt;(args)...) {} virtual void filter() { m_impl.filter(); } private: T m_impl; }; // ------------- int main() { std::unique_ptr&lt;Base&gt; f; int type = 1; switch (type) { case 1: f.reset(new Wrapper&lt;A&gt;("hi from A")); break; case 2: f.reset(new Wrapper&lt;B&gt;("hello from B")); break; } f-&gt;filter(); } </code></pre>
 

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