Search code examples
c++vectorheaderheader-files

declare a c++ vector that can contain all data types defined in a namespace


i have a file called "dtypes.h", that contains some definitions for some numerical data types.

namespace dtypes {
  typedef signed short int int16;      
  // ... some other dtypes
}

i also have another file where i want to create a vector that can contain all this data types (and other vectors). I figured out something like this:

#include <vector>
#include "dtypes.h"

std::vector<std::variant<\* ??? *\>> content; 

I really don't know what to place instead of "???", without having to list all the different data types (without doing std::vector<std::variant<dtypes::int16, dtypes::int32 \*...*\>> content;)
I found some examples here, but it is not exactly what i want.


Solution

  • You don't necessarily need to make the list right there, but you need to make the list somewhere. There's no way avoiding writing the list explicitly.

    Like one of the answers in the linked question suggests, you could use a vector of std::any to store objects of any type. With the obvious drawback of losing the features of a variant type.


    Regarding typedef signed short int int16;, I suggest taking a look at the standard <cstdint> header. It contains aliases for fixed width integers. There's no need to duplicate that effort (unless you need to support pre-C++11 and cannot use open source libraries).