Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting type of a derived class at compile time in C++
    primarykey
    data
    text
    <p>I've been designing classes that all follow the idiom that their shared pointer type is available in their namespace using code like this:</p> <pre><code>class ClassName { public: typedef std::shared_ptr&lt;ClassName&gt; ptr; } </code></pre> <p>making it possible to write code like this:</p> <pre><code>ClassName::ptr p=std::make_shared&lt;ClassName&gt;(); </code></pre> <p>Now, I'd like to factor that code into a base class. It'll let me magically add weak_ptr support in just one place, and will indicate which classes conform to this protocol, and generally make it easier to build out the capabilities.</p> <p>Am I forced into using templates?</p> <p>One way is to follow the enable_shared_from_this&lt;> approach.</p> <pre><code>template &lt;typename T&gt; class SmartPointer { public: typedef std::shared_ptr&lt;T&gt; ptr; typedef std::weak_ptr&lt;T&gt; wptr; } </code></pre> <p>allowing me to define classes like this:</p> <pre><code>class ClassName:public SmartPointer&lt;ClassName&gt; ... </code></pre> <p>but it strikes me as clumsy to have to specify ClassName as the template parameter. What I'd like to do is be able to identify the type of the derived class at compile time, substituting in for derivedClassType() below:</p> <pre><code>class SmartPointer { public: typedef std:shared_ptr&lt;derivedClassType()&gt; ptr; typedef std:weak_ptr&lt;derivedClassType()&gt; wptr; } class ClassName: public SmartPointer ... </code></pre> <p>it seems like the compiler must know that information at compile time as a sort of implied template parameter... This has the added benefit of ensuring the type referenced is the derived class and not a base class.</p> <p>Is there a syntax that would make this possible?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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