0

I have created a generic array-like template to create arrays of different types. Now I need to get user input from a menu about which type of array they are building. I tried having the user enter a number and using that number to pick a string from an array of constant strings. But pretty obviously, that threw a type conversion error. Is there a way to convert the literal string of a type into it's type or refer to a type directly. Thanks!

Here is the code I need to fit a type into at runtime:

SimpleVector<TYPE> myVect = SimpleVector<TYPE>(dataSize);

I also tried this switch statement which I would like better but I am getting a redefinition error.

switch (dataChoice) {
        case 1:
            SimpleVector<int> myVect = SimpleVector<int>(dataSize);
            break;
        case 2:
            SimpleVector<double> myVect = SimpleVector<double>(dataSize);
            break;
        case 3:
            SimpleVector<string> myVect = SimpleVector<string>(dataSize);
            break;
        default:
            break;
 }
Dakota Hipp
  • 749
  • 7
  • 16
  • Templates are a compile-time thing, there's *no way* to specify their parameters in runtime. – Biffen Nov 18 '14 at 07:37
  • This is the first time I've used templates, but I've built the class and tested it with different types of data and it worked fine. Now as per requirements I am supposed to let the user select what type of data they want to enter from a menu. There is no way to do this? I guess I'll have to check with who ever wrote up the assignment requirements and see what they are expecting. Thanks! – Dakota Hipp Nov 18 '14 at 07:49
  • You may want to use a base class of some sort and a `shared_ptr<>` to manage all of that. You could also look into `any` from boost – Niall Nov 18 '14 at 07:50

1 Answers1

0

To get rid of the redefinition error you have to enclose the type definition inside curly brackets

 switch (dataChoice) {
        case 1:
            {
              SimpleVector<int> myVect = SimpleVector<int>(dataSize);
              break;
            }
        case 2:
            {            
               SimpleVector<double> myVect = SimpleVector<double>(dataSize);
               break;
            }
        default:
            break;
  }

TYPE is something the compiler has to know at compilation time: when you try to use a string value instead of a type the compiler will refuse to collaborate.

Refer to What does template <unsigned int N> mean?

Community
  • 1
  • 1
gu1d0
  • 699
  • 5
  • 9
  • such a simple fix to my problem, lol. It did work but I had to duplicate a ton of code under each case. I'm not sure of a cleaner approach I could have taken yet, but I did meet all the requirements I needed to meet. Thanks for the help and sharing that info, confusing, but it seems really powerful. – Dakota Hipp Nov 19 '14 at 08:52