Search code examples
intdoublestdvectorvoid-pointerstypename

Creating a vector of ambiguous type, or escaping variable scope?


I've been given an assignment for a C++ class (heh), which states that I must write a program to perform a certain operation on a vector of data. The data can be either int type or double type. The program must first ask the user which type will be used, and then declare the appropriate vector, and use it for the rest of the program. I was thinking something along these lines:

// Determine type of data values
cout << "What type of values: Int (1), or Double (2)?" << endl
     << "Type: ";
int entry;
cin >> entry;
cin.ignore();

// Execute a typedef accordingly
switch (entry)
{
case 1:
    typedef int TYPE;
    break;
case 2:
    typedef double TYPE;
    break;
default:
    typedef double TYPE;    // Defaults to double
    break;
}

// Declare the vector
vector<TYPE> numbers;

However, this turned out not to work because the typedef statements' scope does not extend past their case in the switch statement.

Something else I tried was to make a void pointer, and then assign it to the proper vector, like so:

// Declare pointer
void * numbers = nullptr;

// Declare both possible vectors
vector<int> intVector;
vector<double> doubleVector;

// Assign pointer to proper vector
switch (entry)
{
case 1:
    numbers = &intVector;
    break;
case 2:
    numbers = &doubleVector;
    break;
default:
    numbers = &doubleVector;
    break;
}

This seems like it should work, right? Well, I get another scope problem: For some reason, I get an "undefined identifier" error on numbers in the switch ... whaaaa?

Then, I tried using a typename variable, but apparently that's not a thing in C++. (something like typename TYPE; ... TYPE = double; ... vector<TYPE> numbers;)

Then came along a clever idea: Write a templated MAKE_VECTOR() function that returns a pointer to a vector of the template's type, and then make it take an argument of the same type to specify the vector type. This is hard to explain; here's the code:

// Returns a pointer to a new vector of a specified type.     template<typename T>
vector<T> * MAKE_VECTOR(T var)
{
    void * ptr;
    vector<T> vec;
    ptr = &vec;

    return ptr;
}

This seemed to work. No syntax errors in the function declaration, but when I go to use it...

void * numbers;

// Determine type
...

switch(entry)
{
case 1:
    numbers = MAKE_VECTOR((int)1);
    break;
    ...
}

// Test
numbers->push_back(2);

Doesn't work. Error: Expression must have pointer-to-class type. I looked online, and realized that I have to dereference the pointer first, right? So I tried (*numbers)->push_back(2);, but nothing like that works either.

I'm out of ideas. What should I do?


Solution

  • Wow. That's weird. I just tried method #2 again, that is, the void pointer, and it worked. WTF, Visual Studio.