FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Soft-typing

 
Post new topic   Reply to topic     Forum Index -> General
View previous topic :: View next topic  
Author Message
ViolentAJ



Joined: 05 Feb 2009
Posts: 56

PostPosted: Mon Mar 30, 2009 8:29 pm    Post subject: Soft-typing Reply with quote

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
View user's profile Send private message
csauls



Joined: 27 Mar 2004
Posts: 278

PostPosted: Tue Mar 31, 2009 6:46 pm    Post subject: Reply with quote

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
View user's profile Send private message AIM Address Yahoo Messenger
Display posts from previous:   
Post new topic   Reply to topic     Forum Index -> General All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
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