Is there a way to store a class in a variable, so that for example, code like this would work?
Code:int main() {
T = vector;
T v;
v.push_back(0);
T = list;
T l;
l.push_back(0);
}
Printable View
Is there a way to store a class in a variable, so that for example, code like this would work?
Code:int main() {
T = vector;
T v;
v.push_back(0);
T = list;
T l;
l.push_back(0);
}
It sounds like you want to write a template, possibly a function template.
For your question, no. For a solution other than a generic answer, you must be more specific about what you're trying to do.
jw232 -
Look into the "typedef" keyword.
http://www.cprogramming.com/tutorial/typedef.html
This may be what you are looking for. It does not use the syntax of
But ratherCode:T = vector;
Code:typedef vector T;
T v;
v.push_back(0);
That's what I was about to suggest, but then I saw he wanted to reassign a different type to T later, which can't be done with typedefs.
I believe the functionality you're looking for is something like the Boost Any class or Variant class; although the syntax of using them would be quite different than what was posted.
Using proper Object Oriented techniques, you should be able to accomplish this with an interface, right?
If by "interface" you mean inheritance and polymorphism with an abstract base class that is a pure interface, then probably yes. It really depends on what jw232 actually wants to do.Quote:
Originally Posted by neandrake
prog-bman: exactly. same thing as his description, just a different syntax. or you can use an interface/adapter/etc. my point was how to accomplish his goal. perhaps if he elaborated at the bigger issue he is trying to solve, there might be a better means.
Boost Any class or Variant class don't really support this kind of thing.
I agree that interfaces are generally a good way to do this. However, these are intrusive to the types that can be assigned, so you would have to wrap library classes and methods in your own classes, to get it to work.
The ideal way to do this is to have a type-class that tells you that list and vector both have compatible push_back() methods, so that you can have a common interface to them without a class wrapper. There would still be separate code that says that the two are similar, but it would not require unwrapping the object to use it in a different way. This feature is coming up in the form of Concepts in C++0x.