Worst ideas/features in programming languages?
bauss
jj_1337 at live.dk
Thu Oct 14 11:54:49 UTC 2021
On Thursday, 14 October 2021 at 11:06:00 UTC, JN wrote:
>
> Named constructors as a replacement for factory static methods:
>
> ```d
> class Angle {
> this.fromDegrees(float deg) { ... }
> this.fromRadians(float rad) { ... }
> }
>
> Angle a = new Angle.fromDegrees(90.0f);
> ```
>
You can somewhat hack your way to it, by generating static
functions at compile-time.
Of course they're not real constructors, so immutable cannot be
used and you can't utilize it like `new Angle.fromDegrees(90.0f)`
and will have to do it like `Angle.fromDegrees(90.0f)` instead.
Example:
```d
class Angle {
private:
this(){}
@Ctor void _fromDegrees(float deg) {
writeln("from degrees");
}
@Ctor void _fromRadians(float rad) {
writeln("from radians");
}
mixin NamedConstructors!Angle;
}
void main()
{
auto a = Angle.fromDegrees(90.0f);
auto b = Angle.fromRadians(90.0f);
}
```
Implementation of the hacky stuff:
```d
struct Ctor {}
template ParametersFullyQualified(alias fun)
{
Tuple!(string,string)[] produceIndexed(T)(T[] a, T[] b)
{
Tuple!(string,string)[] produced = [];
if (a.length == b.length)
{
foreach (i; 0 .. a.length)
{
produced ~= tuple(a[i], b[i]);
}
}
return produced;
}
enum ParametersTypeArray =
Parameters!(fun).stringof[1..$-1].split(", ");
enum ParameterNamesArray = [ParameterIdentifierTuple!(fun)];
enum ParametersFullyQualified =
produceIndexed(ParametersTypeArray, ParameterNamesArray).map!(t
=> t[0] ~ " " ~ t[1]).join(", ");
}
mixin template NamedConstructors(T)
{
public:
static:
static foreach (member; __traits(derivedMembers, T))
{
static if (mixin("hasUDA!(" ~ T.stringof ~ "." ~ member ~
", Ctor)"))
{
mixin(T.stringof ~ " " ~ member[1 .. $] ~ "(" ~
ParametersFullyQualified!(mixin(T.stringof ~ "." ~ member)) ~ ")
{ auto o = new " ~ T.stringof ~ "(); o." ~ member ~ "(" ~
[ParameterIdentifierTuple!(mixin(T.stringof ~ "." ~
member))].join(", ") ~ "); return o; }");
}
}
}
```
More information about the Digitalmars-d
mailing list