How to store a pointer to class contructor
Jacob Carlborg
doob at me.com
Fri Dec 25 12:32:58 UTC 2020
On Thursday, 24 December 2020 at 10:23:09 UTC, Dmitriy Asondo
wrote:
> I expect code like this:
> ----------------------
> class OloloService {}
> class BlablaService {}
>
> auto servicesList = [OloloService, BlablaService];
> auto serviceInstance = new servicesList[1](args);
> ----------------------
Here's a slightly different version that I think is closer to
your original example:
import std;
interface Service {}
mixin template Constructor()
{
this(int a)
{
}
}
class OloloService : Service
{
mixin Constructor;
}
class BlablaService : Service
{
mixin Constructor;
}
Service function(int) create(T)()
{
return a => new T(a);
}
void main()
{
auto servicesList = [create!OloloService,
create!BlablaService];
auto serviceInstance = servicesList[1](3);
writeln(serviceInstance);
}
Since D is a statically typed language you need a form of base
type if you want to store a list of values of different types. In
this case, the base type is `Service`. If you want to have a
constructor, as you do in your original example, the constructor
needs to have the same signature for all types, the mixin
template helps with that.
You can use a tuple as well to store different values of
different types. But then everything need to be known at compile
time. That is, the index, in your case.
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list