Reputation: 235
so i have the following situation. Basically i want to know if it's possible to declare an object of a template class without knowing it's type, or is there another approach i can use for a situation like this.
template <class T> class SomeTemplateClass{
vector<T> v;
}
int main(){
--- Here is where i want to declare the object ---
SomeTemplateClass o;
cin >> eType;
--- Type is not determined until some user input---
if (eType == "int"){
o = SomeTemplateClass<int> (size);
}
else if (eType == "char") {
o = SomeTemplateClass<char> (size);
}
else if (eType == "float") {
o = SomeTemplateClass<float> (size);
}
The type has to be passed as standard input as this is a requirement of the assignment.
EDIT: Ignoring everything else, my problem is that i want to create a vector of type T where T is determined at run-time via user-input. Is this possible at all, and if not what is an acceptable solution
Upvotes: 0
Views: 103
Reputation:
Well, from reading your comment I figured out you'd want something like that
template<typename T>
class myclass {
vector<T> v;
... other methods
};
template<typename T>
void do_something_cool_with_myclass(myclass<T> obj)
{
//do something with obj, type independently
}
int main() {
...
cin >> type; //get type from user somehow
switch (type) {
case int:
myclass<int> obj;
do_something_cool_with_myclass<int>(obj);
....
}
}
You don't waste memory and can process your data without knowing it's type on compile time.
Upvotes: 1