Named constructors

Neia Neutuladh neia at ikeran.org
Thu Jan 10 19:02:53 UTC 2019


On Thu, 10 Jan 2019 10:12:24 -0800, Ali Çehreli wrote:

> On 01/10/2019 06:35 AM, JN wrote:
> 
>  > the real cost is the fact that you have to create all those structs
>  > meticulously and you can only use that with functions that expect
>  > such usage.
> 
> Weka uses the generic TypedIdentifier for integers:
> 
>    https://github.com/weka-io/mecca/blob/master/src/mecca/lib/
typedid.d#L532
> 
> Ali

Which can be done equally well with std.typecons.Typedef. It still has a 
lot of the same issues as custom structs, but at least you can use a 
different module's named arg structs as long as they're not doing anything 
funky.

Here's a slightly better version:

---
struct Named(T)
{
  template opDispatch(string name)
  {
    alias opDispatch = Typedef!(T, T.init, name);
  }
}
struct Arg
{
  template opDispatch(string name)
  {
    alias opDispatch = makeTypedef!name;
  }
}
template makeTypedef(string name)
{
  Typedef!(T, T.init, name) makeTypedef(T)(T value)
  {
    return Typedef!(T, T.init, name)(value);
  }
}
---

Usage:

---
void foo(Named!int.age a, Named!string.name b)
{
  writefln("name: %s age: %s", b, a);
}
void main()
{
  foo(Arg.age(12), Arg.name("Rydia"));
}
---

Something like that is the best you're likely to get with the struct-per-
argument model.


More information about the Digitalmars-d mailing list