Note that there are some explanatory texts on larger screens.

plurals
  1. POVariant implementation like boost::any with auto-conversion support
    primarykey
    data
    text
    <p>I want to implement a variant class that can store any datatype (like boost::any) but with the support of datatype conversion. For example, </p> <pre><code>Variant v1(int(23)); can be converted to bool via v1.get&lt;bool&gt;() using Conv&lt;int, bool&gt;, Variant v2(CustomT1()); to CustomT2 via Conv&lt;CustomT1, CustomT2&gt; and so on. </code></pre> <p>Here is the current implementation, based on the idea of boost::any:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;memory&gt; #include &lt;stdexcept&gt; template&lt;typename Src, typename Dest&gt; struct Conv { /* static? */ Dest convert(const Src&amp; src) const { throw std::runtime_error("type cast not supported"); } }; template&lt;&gt; struct Conv&lt;int, bool&gt; { bool convert(const int &amp;src) const { return src &gt; 0; } }; class IStoredVariant {}; template&lt;typename T&gt; struct variant_storage : public IStoredVariant { variant_storage(const T&amp; value) : m_value(value) {} T&amp; getValue(void) { return this-&gt;m_value; } const T&amp; getValue(void) const { return this-&gt;m_value; } template&lt;typename U&gt; U make_conversion(void) const // just an idea... { return Conv&lt;U, T&gt;().convert(this-&gt;getValue()); } protected: T m_value; }; class Variant { public: template&lt;typename T&gt; Variant(const T&amp; value) : m_storage(new variant_storage&lt;T&gt;(value)) {} IStoredVariant&amp; getImpl(void) { return *this-&gt;m_storage; } const IStoredVariant&amp; getImpl(void) const { return *this-&gt;m_storage; } std::auto_ptr&lt;IStoredVariant&gt; m_storage; template&lt;typename T&gt; T get(void) const { const IStoredVariant &amp;var = this-&gt;getImpl(); // ???????????? // How to perform conversion? } template&lt;typename T&gt; void set(const T &amp;value) { this-&gt;m_storage.reset(new variant_storage&lt;T&gt;(value)); } }; int main(void) { Variant v(int(23)); bool i = v.get&lt;bool&gt;(); } </code></pre> <p>From the get&lt;> template method, I only have access to an IStoredVariant pointer, but I need to know the concrete type to choose the Converter&lt;>. Is there any design pattern or workaround to solve this problem?</p>
    singulars
    1. This table or related slice is empty.
    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