问题
I hope my question is clear. I would like to do something like this:
TYPE tipo = int;
tipo = float;
To later be able to do other things like these:
void* ptr = new tipo();
cout << *(tipo*)ptr;
It's, basically, to determinate the type of a void-pointer (or a variant
-object, or a any
-object) and its de-reference, but in execution time.
This is my whole problem: I'm trying to create an array of any type of variable (simulating the RAM of a PC for a compiler). For this I'm using void pointers and other array where I store an integer which represents the type of the element was stored in the first array. So then I can cast properly the element when it's required. This code works, but of course it's no so functional because I would have to use all the switch-case each time I have to recover an element from my array:
#define INT 0
#define FLOAT 1
#define BOOL 2
int main(void)
{
void* ram[] = { new float(2.5), new float(5.8), new bool(true), new int(8) };
int tipo[] = { FLOAT, FLOAT, BOOL, INT };
int i = 1;
int salida;
switch (i)
{
case INT: salida = *(int*)ram[i]; break;
case FLOAT: salida = *(float*)ram[i]; break;
case BOOL: salida = *(bool*)ram[i]; break;
}
cout << salida;
return 86;
}
I wonder if I coudl have an "array of types", so I coudl do something like this
int main(void)
{
void* ram[] = { new float(2.5), new float(5.8), new bool(true), new int(8) };
TYPE tipo[] = { float, float, bool, int };
int i = 1;
int salida = *(tipo[i]*)ram[i];
cout << salida;
return 86;
}
Is it possible? If no, how would you solve this problem?
回答1:
Your first block of code is basically OK but not good for performance because there is overhead associated with every new
allocation, and you're paying that price for every single element of data.
Your second block of code is not really viable, at least not in the way you propose.
There is a better solution: a vector of variants. In your case:
std::vector<std::variant<int, float, bool>> values;
You can store all three types in here, like this:
values.emplace_back(2.5f);
values.emplace_back(5.8f);
values.emplace_back(true);
values.emplace_back(8);
This container is resizable, holds all your data in a single large allocation (which for small types greatly reduces allocation overhead), and can be expanded to support more types with no extra work.
Ref: https://en.cppreference.com/w/cpp/utility/variant
回答2:
While John's answer is definitely a good suggestion about how you should approach your problem, to strictly answer your title question, there is a std::type_info class which stores type information. It allows e.g. to compare types or print their names.
You can use typeid() to retrieve it:
#include <typeinfo>
#include <iostream>
int main()
{
const std::type_info& info = typeid(float);
std::cout << info.name() << std::endl;
return 0;
}
来源:https://stackoverflow.com/questions/63212707/can-a-type-of-variable-be-an-object-in-c