1 /* Create classes from their modules and names.
3 * Copyright: Copyright (C) D Language Foundation 2023
4 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
5 * Authors: Walter Bright, Steven Schveighoffer
6 * Source: $(DRUNTIMESRC core/_factory.d)
12 * Create instance of class specified by the module symbol and a string
13 * representing the name of the class.
14 * The class must either have no constructors or have
15 * a default constructor.
17 * mod = symbol representing the module that the class is in
18 * classname = string representing the name of the class
33 * auto c = cast(C)factory!(foo.bar)("C");
34 * assert(c !is null && c.x == 10);
38 Object
factory(alias mod
)(string classname
)
40 foreach(cl
; _getModuleClasses
!mod
)
42 if (cl
.stringof
== classname
)
43 return cl
.classinfo
.create();
50 Object valid_obj
= factory
!object("Object");
51 Object invalid_obj
= factory
!object("__this_class_doesnt_exist__");
53 assert(valid_obj
!is null);
54 assert(invalid_obj
is null);
57 /**************************************
58 * Retrieve as a tuple all the types of the top level classes in the module mod.
60 private template _getModuleClasses(alias mod
) {
61 alias result
= _AliasSeq
!();
62 static foreach(m
; __traits(allMembers
, mod
))
63 static if(is(__traits(getMember
, mod
, m
) == class))
64 result
= _AliasSeq
!(result
, __traits(getMember
, mod
, m
));
65 alias _getModuleClasses
= result
;
68 private template _AliasSeq(TList
...) { alias _AliasSeq
= TList
; }