I want a function that creates an array for testing purposes:
Since C++ is a statically typed language, you cannot really do this in a simple way. You cannot determine types at runtime, these are fixed as soon your program has been compiled.
The closest thing you can get for your case IMHO, is using something like a boost::variant or boost::any.
it can be done using void*
but in that case you need to do type casting yourself (as pointed out by @Rob) i.e. using reinterpret_cast
operator or similar. Here is a simple example with void*
void* vector(){
int t;
int op;
cout << "Size: \n";
cin >> t;
cout << "Select type\n";
cin >> op;
switch(op) {
case 0:
// Create the array with the selected option...
return reinterpret_cast<void*>(new int[t]);
case 1:
// Create the array with the selected option...
return reinterpret_cast<void*>(new double[t]);
default:
// Other stuff;
return reinterpret_cast<void*>(new float[t]);
}
}
Note: you can look at working of malloc()
function, it always returns void*
to allocated memory and you have to type cast it yourself e.g malloc(sizeof(int)*t)
The simple answer is that you cannot, because data types need to be specifically declared at compile time.
If you can use boost libraries,
boost::variant<int,float,double> vec;
can suit your needs.
You cannot use union
because std::vector
is not a POD (Plain Old Datatype).
EDIT:
As @Rob pointed out:
Void pointers need to be converted into a pointer to something else - at compile time - before they can be used that way. So the answer is still "cannot" use void pointers to make a variable data type.
I think you should re-think your design.
Rather than trying to write a function that returns an array of user-defined type to test. I would instead call a different test function depending on the user choice.
The test function can be templated to avoid code duplication:
#include <vector>
#include <iostream>
template<typename T>
void doTest(unsigned size) {
std::vector<T> data(size);
// Do the actual test on the data...
}
int main() {
unsigned size;
std::cout << "Size: \n";
std::cin >> size;
int op;
std::cout << "Select type\n";
std::cin >> op;
switch(op) {
case 0:
doTest<int>(size);
break;
case 1:
default:
doTest<float>(size);
}
}
If you really want to return your array from a function you could wrap it in a polymorphic type. But to actually do anything with the array you would need to call a virtual method on the polymorphic type so I don't see how it buys you anything over calling a test function directly.