View previous topic :: View next topic |
Author |
Message |
ViolentAJ
Joined: 05 Feb 2009 Posts: 56
|
Posted: Mon Mar 30, 2009 8:29 pm Post subject: Soft-typing |
|
|
Is it possible to soft-type in D?
I'm trying to simulate a stack, and I'd like to know if I can make an array of type Object?
for example: Object[] x;
instead of having to do int[] x, or string[] x.
Is this possible? Then, the user that is writing the client for this stack can decide what types of objects it holds. |
|
Back to top |
|
|
csauls
Joined: 27 Mar 2004 Posts: 278
|
Posted: Tue Mar 31, 2009 6:46 pm Post subject: |
|
|
Generally this is what templates are for.
Code: |
class Stack (T) {
// ...
private T[] data ;
}
// I want a stack of ints.
auto mystack = new Stack!(int);
mystack.push(123);
|
If you are wanting to have a single stack type that can hold any value... things get more interesting. You'll need to use an open variant. For D1, this means Tango's Variant (tango.core.Variant) or Phobos' Box (std.boxer). For D2, its Phobos' Variant (std.variant).
You can't just use Object[] because, unlike in Java or C# or the like, not everything is an object; only types defined by classes. So, a stack of Object's is fine if all you want to store is class instances; but otherwise it just won't work. _________________ Chris Nicholson-Sauls |
|
Back to top |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|