On Tuesday, 1 October 2024 at 17:30:20 UTC, H. S. Teoh wrote:
> On Tue, Oct 01, 2024 at 04:30:27PM +0000, Salih Dincer wrote:
> Please add this to your MyCon structure:
alias value this;
// assert(num1 == 3.14);
And test it like this too, I think it's awesome!
[...]
IMO it's not a good idea to recommend the use of alias this
. It's a neat trick that solves the short-term problem...
You may be right about the alias. Let's go a little further and put the convertToHex() function between the template and the struct:
template MyCon(T, string str = "0")
{
MyCon convert = str;
struct MyCon
{
T value; //alias value this;
this(R)(R data)
{
import std.conv : to;
value = data.to!T;
}
mixin DownRange;
}
enum _input = str;
string convertToHex()
{
import std.string : format;
return _input.format!"%-(%02X%)";
}
}
import std.stdio;
void main()
{
mixin MyCon!(double, "3.141") piNumber;
piNumber.convertToHex().write(": ");
piNumber.convert.writeln;
auto iNumber = MyCon!double("0.123");
piNumber.convertToHex().write(": ");
iNumber.value.writeln;
// mixin MyCon!(int, "123") testError;
mixin myStatement!(int, "Hello");
assert(_value == 42); // no error
mixin myStatement!(double, "D!");
// assert(_value == 42);
}
template myStatement(T, string value = "")
{
auto doIt()
{
T.stringof.writeln(": ", value);
return 42;
}
auto _value = doIt();
}
template DownRange()
{
auto empty() => value <= 0;
auto front() => value;
auto popFront() => --value;
}
struct S
{
int value;
mixin DownRange;
}
I also added another template called DownRange (InputRange functions) inside a template. Since the structures of this mixin are static codes, unfortunately everything looks like const and cannot be changed. Please play around in the playground. I tried to show many things in the code above.
Here is the output of the code:
/*
332E313431: [3.141, 2.141, 1.141, 0.141]
332E313431: 0.123
int: Hello
double: D!
*/
Please note iNumber, not piNumber.
SDB@79