0

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.

Giuppox
  • 1,393
  • 9
  • 35
  • I think this is a duplicate of https://stackoverflow.com/a/26208947/7611357. You have a good detailed answer [here](https://stackoverflow.com/a/26208947/7611357) – Rshad Zhran Feb 03 '21 at 13:41
  • the q&a you link has lots of answers that could apply here. You sould explain why you dont want them, otherwise we will just repeat here what has already been said there – 463035818_is_not_an_ai Feb 03 '21 at 13:42
  • Why? This question is example of [XY problem](http://xyproblem.info/). In C++ there is no way to reflect all symbols in namespace. – Marek R Feb 03 '21 at 13:51

2 Answers2

3

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).

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

You can store all the items using a std::vector, by submitting std::any as a template parameter to the std::variant. It would look something like this,

std::vector<std::variant<std::any>> arr;
arr.push_back("Hello World");
arr.push_back(10);
arr.push_back(10.0f);
arr.push_back(10.0);

auto any = std::get<std::any>(arr[0]);
auto pTypeName = any.type().name();    // You can get the name of the type to match and cast if your not sure about the index.
std::string str = std::any_cast<const char*>(any);

Now you can use this if using std::variant is mandatory. If not you can use a std::vector of std::any as the other answer stated.

D-RAJ
  • 3,263
  • 2
  • 6
  • 24