Note that there are some explanatory texts on larger screens.

plurals
  1. POThis template code will not compile. Any ideas?
    text
    copied!<p>I got this code from rhalbersma, but it does not compile in VC 2010. I don't know what I'm doing wrong.</p> <pre><code>template&lt;typename Derived&gt; struct enable_crtp { private: // typedefs typedef enable_crtp Base; public: // casting "down" the inheritance hierarchy Derived const* self() const { return static_cast&lt;Derived const*&gt;(this); } // write the non-const version in terms of the const version // Effective C++ 3rd ed., Item 3 (p. 24-25) Derived* self() { return const_cast&lt;Derived*&gt;(static_cast&lt;Base const*&gt;(this)-&gt;self()); } protected: // disable deletion of Derived* through Base* // enable deletion of Base* through Derived* ~enable_crtp() { // no-op } }; template&lt;typename FX&gt; class FooInterface : private enable_crtp&lt; FX &gt; { public: // interface void foo() { self()-&gt;do_foo(); } }; class FooImpl : public FooInterface&lt; FooImpl &gt; { private: // implementation friend class FooInterface&lt; FooImpl &gt; ; void do_foo() { std::cout &lt;&lt; "Foo\n"; } }; class AnotherFooImpl : public FooInterface&lt; AnotherFooImpl &gt; { private: // implementation friend class FooInterface&lt; AnotherFooImpl &gt;; void do_foo() { std::cout &lt;&lt; "AnotherFoo\n"; } }; template&lt;template&lt;typename&gt; class F, int X&gt; class BarInterface : private enable_crtp&lt; F&lt;X&gt; &gt; { // interface void bar() { self()-&gt;do_bar(); } }; template&lt; int X &gt; class BarImpl : public BarInterface&lt; BarImpl, X &gt; { private: // implementation friend class BarInterface&lt; ::BarImpl, X &gt;; void do_bar() { std::cout &lt;&lt; X &lt;&lt; "\n"; } }; int main() { FooImpl f1; AnotherFooImpl f2; BarImpl&lt; 1 &gt; b1; BarImpl&lt; 2 &gt; b2; f1.foo(); f2.foo(); b1.bar(); b2.bar(); return 0; } </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