Compile time values & implicit conditional mixin, as an alternative to tertiary operator hell and one-compile-time functions.
Sebastiaan Koppe
mail at skoppe.eu
Sat Jan 16 14:56:18 UTC 2021
On Saturday, 16 January 2021 at 14:20:19 UTC, Paul wrote:
> On Saturday, 16 January 2021 at 04:13:12 UTC, Paul Backus wrote:
>> You can use immediately-invoked function literals to work
>> around all of these issues:
>>
>> enum string values = () {
>> string result = "value.x";
>> if (L != 1) { result ~= ",value.y"; }
>> if (L != 2) { result ~= ",value.z"; }
>> if (L != 3) { result ~= ",value.w"; }
>> return result;
>> }(); // call the function we just defined
>>
>> enum string kind = () {
>> if (is(S == uint)) { return "ui"; }
>> else if (is(S == float)) { return "f"; }
>> else { assert(is(S == double)); return "d"; }
>> }();
>
> This seems like a workaround for defining a function, and seems
> semantically strange to me. You're still restricted to
> immediate local 'onelines'. Not that my issue requires
> non-oneliners, but were my use case to have to mix/match the
> string depending on compile time conditions, you'd have to
> create either many almost identical function, or ones with
> additional reoccuring conditions, instead of building a
> variable at compile time, with conditionals occuring only once.
>
> Thanks for the suggestion nontheless, that may be more
> organized for my current (rougly simple, I may need more
> complexity later on) case. 🙂
you can also use CTFE. Generate the values in a normal function,
assign it to an enum.
---
string generateValues(uint L)() {
string result = "value.x";
if (L != 1) { result ~= ",value.y"; }
if (L != 2) { result ~= ",value.z"; }
if (L != 3) { result ~= ",value.w"; }
return result;
}
enum string values = generateValues!3();
pragma(msg, values);
void main(){};
---
More information about the Digitalmars-d
mailing list