Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a few ways you could do this. A <a href="http://www.cplusplus.com/doc/tutorial/other_data_types/" rel="nofollow">union</a> lets you store multiple different types of data in the same memory location, but the space used will be the space required by the largest data type, and you'll have to know the type when you add it or remove it:</p> <pre><code>// This will take 8 bytes because a long is int64_t is 8 bytes union MyUnion { int32_t regular_int; int64_t big_int; } MyUnion var; // Stores an int32_t in var var.regular_int = 100; // replaces it wiht an int64_t var.big_int = 100; </code></pre> <p><a href="http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html" rel="nofollow">Boost variant</a> provides a nice object oriented wrapper around the idea of a variant and allows you to include non-POD types.</p> <p>You can also create your own set of classes that allows you to do this and provide functionality that is useful for your application. For example, if you need to be able to write all value types to stdout the following might be useful:</p> <pre><code>class MyVariant { public: virtual void print() = 0; } template&lt;class T&gt; MyVariantType public MyVariant { private: private T data_; public: MyVariantType(T data) { data_ = data; } virtual void print() { cout &lt;&lt; data_; } } MyVariant* var = new MyVariantType&lt;int&gt;(100); var-&gt;print(); var = new MyVariantType&lt;string&gt;("hello world"); var-&gt;print(); </code></pre> <p>Finally, if you're truly desperate, you can use void* pointers and do casting, but this isn't recommended.</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