Object.factory

DanO dsstruthers at nospamplease.yahoo.com
Tue Sep 25 15:25:59 PDT 2007


Deewiant Wrote:

> Arlen wrote:
> > There was the 'factory' static method introduced in D some time ago. I haven't been succeeding in creating a single instance of any of my classes. The result of the function call is always 'null'.
> > 
> > What's going on?
> > 
> > An example code:
> > 
> > ---------------------------------------------
> > import std.stdio;
> > 
> > alias char[] string;
> > 
> > int main(string[] args)
> > {
> > 	MyClass a = cast(MyClass) Object.factory("MyClass");
> > 
> > 	if(a !is null)
> > 	{
> > 		a.name = "Arlen";
> > 		a.family_name = "Keshabyan";
> > 
> > 		writefln(a.name ~ " " ~ a.family_name);
> > 	}
> > 	else
> > 		writefln("cannot create the MyClass class instance!");
> > }
> > 
> > 
> > 
> > class MyClass
> > {
> > private:
> > 
> >     string m_name;
> >     string m_family_name;
> > 
> > public:
> > 
> >     this()
> >     {
> >     	m_name = "";
> >     	m_family_name = "";
> >     }
> > 
> >     string name(){return m_name;}
> >     void name(string value){m_name = value;}
> > 
> >     string family_name(){return m_family_name;}
> >     void family_name(string value){m_family_name = value;}
> > }
> > 
> > 
> 
> You need to specify the fully qualified name, i.e. precede "MyClass" with the
> module name and a period.
> 
> For instance, if your code is in a file called foo.d, or you have a "module
> foo;" in the code, pass "foo.MyClass" to Object.factory.
> 
> Note that if you know the class name at compile time, you don't need
> Object.factory: you can use a mixin statement instead, which works just as you'd
> expect and without runtime costs:
> 
> mixin("MyClass a = new MyClass;");
> 
> -- 
> Remove ".doesnotlike.spam" from the mail address.


I have found that this works quite well for non-templated classes, but templated classes don't seem to behave.  I am using the ClassInfo's name property to get the string, and that doesn't work.

<code>
class TDict(T)
{
    T[char[]] dict;
}

char[] tInfoName = TDict!(int).classinfo.name; // returns TDict!(int).TDict

Object o = Object.factory(tInfoName);   // returns null
</code>

I have not tried 'Object.factory("TDict!(int)")'; it may work just fine.

Anyone have any idea if this is supposed to work or is supported?

Thanks! 



More information about the Digitalmars-d mailing list