I want a function that creates an array for testing purposes:
So this would be the example code
**type** vector()
{
int t;
int op;
cout << "Size: \n";
cin >> t;
**type** * v = new **type**[t]
cout << "Select type\n";
cin >> op;
switch(op) {
case 0:
// Create the array with the selected option...
return * v;
case 1:
// Create the array with the selected option...
return * v;
default:
// Other stuff;
}
}
So the question would be what type of function should I use, and also what type of dynamic variable should I declare as v.
And also how to use it later on other functions once correctly done.
Thanks.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With