Note that there are some explanatory texts on larger screens.

plurals
  1. POtemplate typename question
    text
    copied!<p>I have a problem with template and wondering is there a possible way to achieve what I wanted to do. Here is my question.</p> <pre><code>template &lt;typename T&gt; class A { public: typedef T* pointer; typedef const pointer const_pointer; A() {} template &lt;typename D&gt; A(const D&amp; d) { // how can I store the D type // so I can refer it later on // outside of this function } }; </code></pre> <p>ok here is a more complete code of what I wanted to do (it might not be compilable)</p> <pre><code> class C { public: virtual ~C(){} virtual void* get_d() = 0; private: }; template &lt;typename T, typename D&gt; class Cimpl : public C { public: Cimpl() :t() ,d() {} Cimpl(const T&amp; t, const D&amp; d) :t(t) ,(d) {} void* get_d() { return &amp;reinterpret_cast&lt;D&amp;&gt;(d); } private: T t; D d; }; class B { public: B() :p(0) {} template &lt;typename T, typename D&gt; B(const T&amp; t, const D&amp; d) :p(0) { try { p = new Cimpl&lt;T, D&gt;(t, d); } catch(...) { d(p); } } void* get_d() { return (p != 0) ? p-&gt;get_d() : 0; } ~B() { delete p; } private: C* p; }; template &lt;typename T&gt; class A { struct example_d { }; public: typedef T* pointer; typedef const pointer const_pointer; A() {} template &lt;typename D&gt; A(const T&amp; t) :b(t, example_d()) { } template &lt;typename D&gt; A(const T&amp; t, const D&amp; d) :b(t, d) { // how can I store the D type // so I can refer it later on // outside of this function } // not type safe...as user can cast to any type // if I can store the type user pass in previous // then I can use it back template &lt;typename T&gt; T* get_d() { reinterpret_cast&lt;T*&gt;(b.get_d()); } private: B b; }; </code></pre> <p>So I can use the class like</p> <pre><code>1)A&lt;int&gt; a(1);// with example_d as D 2)A&lt;int&gt; b(1, another_d()) // with another_d </code></pre> <p>I can change the template to take 2 parameters and use default parameter for 2nd type to be example_d. So I can achieve 1) but not 2). As I will have to code this way</p> <pre><code>A&lt;int, another_d&gt; b(1, another_d()); </code></pre> <p>a bit too long to type...</p>
 

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