title: Pass any data type to function in C++
body: <p>For the purposes of one of my projects I would like to make a <code>typedef struct</code> that can contain any type of data. I made one that stores in an <code>enum</code> what kind of data it is holding, as well as a <code>void *</code> that actually holds the data.</p>
  
  <p>In my current attempts it worked quite well with ints, but when I tried to add other types like <code>std::string</code> or <code>float</code> it didn't work too well.</p>
  
  <p>I've tried a few different methods of trying to put the data into the <em>container</em> and get it out, but none so far have worked for everything.</p>
  
  <p>What is the best way to do this? I would like to stuff any type of data into a structure and be able to retrieve the data in the same form.</p>
  
  <p>Edit:</p>
  
  <pre><code>typedef struct{
      DataTypeInt,
      DataTypeFloat,
      DataTypeString
  }DataType;
  
  typedef struct{
      DataType type;
      void *data;
  }Data;
  </code></pre>
  
  <p>At first I was testing only with ints and I would simply use <code>(void *)foo</code> to input the data. Then put <code>(int)bar.data</code> to get the data out. This worked marvellously with <code>int</code> types but i received compiler errors if I tried <code>std::string</code> or <code>float</code></p>
  
  <p>After fumbling around with different pointer and casting configurations, and searching the internet, I ended up putting simply <code>foo.data = &amp;bar</code> to input the data and <code>float foo = *(float*)bar.data</code> to get the data out. This didn't give any errors, but the data didn't come out correctly. Any <code>int</code> or <code>float</code> that came through the other side would be <code>0</code> and strings would be random symbols.</p>
  
  <p>I also tried both of those methods with a wrapper struct to contain each data type and then pass that as data.</p>