Instantiating a class with different types at runtime

Marduk via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 28 23:04:10 PST 2016


On Sunday, 27 November 2016 at 21:06:58 UTC, ag0aep6g wrote:
> Turn Example into a template, and add a free function for nice 
> construction:
>
> ----
> class Example(Type_left, Type_right)
> {
>     /* ... as you had it ... */
> }
>
> Example!(L, R) makeExample(L, R)(L x, R y)
> {
>     return new Example!(L, R)(x, y);
> }
>
> void main()
> {
>     auto foo = makeExample(1, 2);
>     auto bar = makeExample(3, "baz");
> }
> ----
>
> Note that Example is not a type, but a template. That means, 
> foo and bar have different types, because their types are 
> different instantiations of the Example template. You can 
> define a common interface or (possibly abstract) base class.

Great! Many thanks.


More information about the Digitalmars-d-learn mailing list