Re: betterC DLL in Windows
On Monday, 6 February 2023 at 15:54:40 UTC, bachmeier wrote: This is the specification for the D Programming Language. I've been bitten by that a few times over the years, though to be honest, I'm not sure of the relationship of the spec to documentation. The Phobos documentation and compiler documentation appear to be actual documentation, in the sense that you can trust it to be accurate, and if not it's a bug. I see... I guess I was confused by the title of the link, "Language Reference" on the Docs page, and didn't look carefully at the URL or the text after that.
Re: betterC DLL in Windows
On Sunday, 5 February 2023 at 19:00:16 UTC, Richard (Rikki) Andrew Cattermole wrote: So LDC with druntime and yes GC turned on is good enough right now that you can probably make it work without too much effort. You don't necessarily have to limit yourself to -betterC. In fact if you don't, you have access to PyD[0] which can handle the interop stuff for you. I haven't personally used it, but it might work for your use case :) [...] But yeah if you can avoid having to create bindings for stuff (such as glib which we have bindings for), or wrappers ext. do so. That way you can do more of the fun things! Sounds quite convincing, I think I might do it this way, instead of with betterC. Not needing additional python bindings does sound like a big plus. Thanks.
Re: betterC DLL in Windows
On Sunday, 5 February 2023 at 00:27:19 UTC, Richard (Rikki) Andrew Cattermole wrote: On 05/02/2023 1:20 PM, Adam D Ruppe wrote: Even module imports can fail because betterC disables outputting the module data info, even if it would otherwise be required by language rules, despite it not using the druntime. This only affects you if you use full D to interact with -betterC code. Even then it is very easy to work around. https://github.com/Project-Sidero/basic_memory/blob/main/source/sidero/base/moduleinfostubs.d -betterC DLL's do work with full D executables. If all you need it for is gluing some stuff together don't listen to Adam about it not working, because it absolutely does and quite usable if you're not expecting there to be a GC. I'm repeating myself, but I'm very happy to see so many helpful responses to my newbie question. It gives me a good feeling about the community here. As I wrote, I'd like to use D only in a limited way, for now. My project actually interfaces Python and glib/gstreamer, the glue being provided by my C code. What I'd like to do is to improve on my C code, inspired by [this interview](https://dlang.org/blog/2017/08/23/d-as-a-better-c/). I don't want to introduce another GC or runtime into the picture, and I probably don't need to call any D libraries. Python -> my C code -> glib/gstreamer C libs to Python -> C improved by betterC -> glib/gstreamer C libs On the surface, betterC seems to be perfect for this case. How would YOU do it (Adam, Richard)? BtW, gstreamer also has D bindings, and maybe in the future I'll use those. I suspect that Adam's suggestions have a stronger relevance to that case, right?
Re: betterC DLL in Windows
On Sunday, 5 February 2023 at 00:20:24 UTC, Adam D Ruppe wrote: There's a lot of things described in the documentation that don't actually work. D can be an *extremely* productive language if you know which parts to focus on, but most the newer hyped features just don't deliver. The table of contents on the left side of the site is in roughly chronological order. The things near the top are pretty reliable, [...]. The things near the bottom are not reliable. [...] and so on I appreciate all of this... however, as a newcomer, I wish the docs were simply more honest, instead of representing wishful thinking. I guess in any programming language, experience reveals things not present in the docs, but it seems to apply much more acutely here.
Re: betterC DLL in Windows
On Saturday, 4 February 2023 at 19:44:15 UTC, bachmeier wrote: On Saturday, 4 February 2023 at 18:29:41 UTC, Tamas wrote: What's the reason to prefer LDC over DMD? Anyone that cares about performance will use LDC rather than DMD. It's hard to imagine a case where someone would want betterC to avoid the GC, but they wouldn't want to use LDC. When I started using D many years ago, LDC was behind DMD, so you needed to use DMD to have a current compiler. That's no longer true. The only reason I use DMD today is the faster compilation speed when I'm doing a lot of write-compile-debug iterations. Good to know, thank you. The posts I've seen so far online suggesting to start with DMD must've been outdated, then.
Re: betterC DLL in Windows
On Saturday, 4 February 2023 at 18:27:34 UTC, Adam D Ruppe wrote: On Saturday, 4 February 2023 at 18:11:05 UTC, Tamas wrote: Well, as I'm new to D this isn't something I have insight into. Then you'd probably be better off taking my word for it (or even trusting your own limited experience where things worked until you added the switch) and just not using -betterC switch. It is hopelessly broken, but thankfully, it also brings zero benefit, so simply not using it is a viable path forward. I do take your word for it, but now I have to re-evaluate my expectations towards D and perhaps use it for another project. I've got most of my project working in C already, but I was hoping to add some safety and better readability/managability by using some of the convenient features D offers over C. And, of course, learn D in the process. Also, your words give me the impression that I cannot trust the documentation; which isn't a great start into the learning process. I mostly need interop with C libraries and D would only serve as a glue, so I don't really need several features like GC etc. Just don't call those functions and they won't hurt you, aside from adding ~200 KB of size to the dll. On the other hand, the -betterC switch is hurting you - as evidenced by your own attempt working until you added it. It can be evidence of something broken in D as you say (simplified) or of my lack of experience with D - a simple missing include, badly configured PATH, or lack of understanding on my part what SimpleDllMain does.
Re: betterC DLL in Windows
On Saturday, 4 February 2023 at 16:51:36 UTC, Richard (Rikki) Andrew Cattermole wrote: You don't have access to druntime/Phobos stuff at runtime. SimpleDllMain is for initializing and uninitializing druntime. See: https://github.com/Project-Sidero/basic_memory/blob/main/source/sidero/base/dllmain.d You want to only use ldc atm. The defaults right now should most likely "just work" in dub for a single compile + link step (i.e. only a single static library in dll). If you do it manually, you'll want to add the flag ``--fvisibility=public`` to export everything. I'm not sure I understand every bit of it yet, but this looks helpful, thank you. I was able to compile this (based on dllmain.d linked by you) with both DMD and LDC: ```D module WindowsApp1; version (Windows) { version (D_BetterC) { import core.sys.windows.windef : HINSTANCE, BOOL, DWORD, LPVOID; extern (Windows) BOOL DllMain(HINSTANCE hInstance, DWORD ulReason, LPVOID reserved) { return true; } } else { import core.sys.windows.dll; mixin SimpleDllMain; } } export extern (C) void foo() { import core.stdc.stdio : printf; printf("Hello betterC\n"); } ``` What's the reason to prefer LDC over DMD?
Re: betterC DLL in Windows
Hi, thanks for the feedback. I'm happy to see 2 replies so quickly. On Saturday, 4 February 2023 at 17:26:17 UTC, Adam D Ruppe wrote: On Saturday, 4 February 2023 at 16:45:31 UTC, Tamas wrote: export extern (C) void main() mixin SimpleDllMain; No need to ever mix two mains together, the DllMain is the required one. Indeed, that is an oversight on my part. However, that's just a typo I happened to include in my last attempt. I use foo() and others, and .def exporting them etc. Tried various things based on the examples I linked. and they compile without `-betterC`, but fail with link errors when using the switch. then don't use the switch lol -betterC is barely supported and completely useless so better to just not use it. Well, as I'm new to D this isn't something I have insight into. However, this being and advertised feature of the language, I'm surprised to see that you dismiss it so casually. Also, for my project, I mostly need interop with C libraries and D would only serve as a glue, so I don't really need several features like GC etc. `betterC`, at least what I thought it was supposed to be, seemed to be a good fit for what I need. error LNK2019: unresolved external symbol _D4core3sys7windows3dll18dll_process_attachFPvbZb referenced in function DllMain This is just betterC breaking the code. Perhaps, but this doesn't help me much.
betterC DLL in Windows
Hi, I'm new to D and trying my hands on a few simple things. Being able to build a Windows DLL with betterC enabled is of particular interest to me, as I'd need it for a project that I'd like to do in D. I'm trying to follow some examples, such as [this](https://wiki.dlang.org/Win32_DLLs_in_D) and [this](https://tekmoji.com/?post=Calling%20D%20(dlang)%20shared%20libs%20from%20Python%20on%20Windows), and they compile without `-betterC`, but fail with link errors when using the switch. example DLL, or see 2nd link for one without the mixin ```D //WindowsApp1.d module WindowsApp1; import core.sys.windows.windows; import core.sys.windows.dll; export extern (C) void main() { import core.stdc.stdio : printf; printf("Hello betterC\n"); } mixin SimpleDllMain; ``` then ``` dmd -m64 -shared -betterC WindowsApp1.d ``` yields error: ``` error LNK2019: unresolved external symbol _D4core3sys7windows3dll18dll_process_attachFPvbZb referenced in function DllMain error LNK2019: unresolved external symbol _D4core3sys7windows3dll18dll_process_detachFPvbZv referenced in function DllMain error LNK2019: unresolved external symbol _D4core3sys7windows3dll17dll_thread_attachFbbZb referenced in function DllMain error LNK2019: unresolved external symbol _D4core3sys7windows3dll17dll_thread_detachFbbZb referenced in function DllMain ``` I'm not a complete beginner to programming, so I'm guessing the linker is missing a library, but as I'm not familiar with D yet, and these are fairly basic examples that I expected to run without a hitch, I'm a bit confused as to what I should be doing. Shouldn't the system modules provide the link targets themselves? Should I add a parameter to include a windows system library? BtW, I've tried compiling from the command line and from Visual Studio using the visuald extension - I'm assuming the extension makes sure the environment variables are set correctly. When using dmd from the command line, I also tried invoking `dmd2vars64.bat` and `vcvars64.bat` before running dmd.exe to ensure the variables are set. In any case, the build process is successful without `betterC`, so I'm assuming the path/variables are set correctly.
Re: D for microservices
On Thursday, 8 March 2018 at 22:53:11 UTC, aberba wrote: On Thursday, 8 March 2018 at 09:35:08 UTC, Andrew Benton wrote: On Thursday, 8 March 2018 at 07:54:29 UTC, Jacob Carlborg wrote: On Thursday, 8 March 2018 at 07:20:53 UTC, Radu wrote: This guys says that vide.d works https://forum.dlang.org/thread/gikoeutmdyvolfshp...@forum.dlang.org Yes, it's pretty straightforward: 1. Build on Ubuntu, or some other dist 2. Statically link the whole binary with LDC, then you don't need to use Musl 3. Run it on Alpine -- /Jacob Carlborg Looks like that works out much nicer than using alpine as the first stage right now. I'm not sure anyone will be too upset about the extra 7MB. Building directly in alpine will simplify automated builds too. Simple Vibe.d app talking to Redis, packed into docker containers: https://github.com/tam4s/hello-redis The takeaway is that I could not use Alpine as a host image, because I could not build the app statically on ubuntu. warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
Re: vibe.d server in a docker image
On Wednesday, 7 March 2018 at 14:54:22 UTC, aberba wrote: I notice from the Dockerfile you build and copy the binary to alpine directly. Why don't you build and serve from alpine directly? This way the final images won't contain the build environment, thus they are really small: 9 and 12 MB on arm and x86 respectively.
vibe.d server in a docker image
I packaged a hello world vibe.d http server into a docker image. It's only 12 MB, and boots up real fast. I can run this on my ARM based NAS, pretty sweet. docker run -it --publish : tam4s/hello-vibe-x86_64 or docker run -it --publish : tam4s/hello-vibe-armv7l source with build instruction: http://github.com/tam4s/hello-vibe
Re: Fetch and pre-build dub dependencies
On Wednesday, 7 March 2018 at 04:28:11 UTC, Seb wrote: For run.dlang.io, I fetch all dependencies and build them into the Docker image. That has the advantage that executions with dub packages are a lot faster. It's just dub fetch and dub build though. Take a look: https://github.com/dlang-tour/core-exec/blob/master/Dockerfile Thank you for showing your solution! Using dub --single is neat and works well for this!
Fetch and pre-build dub dependencies
I have a Dockerfile to build a vibe.d project. Docker has a nice caching system so it continues building the docker image from the step where it's needed when something changes. This is typically at the step of adding my source files, then building the binary. The problem is that fetching and building vibe dependencies takes a lot of time every time some source files of mine changes. I can pre-fetch dub dependencies, although it's a bit cumbersome as fetch doesn't load dependencies of the given package. RUN dub fetch vibe-d --cache=system RUN dub fetch vibe-core --cache=system RUN dub fetch eventcore --cache=system But there's no easy way to build these dependencies before I add my project source files to the docker image. If I could do that the docker build process would be tremendously faster, as it would be simply skipped automatically by the Docker cache system. Currently 99% of the time spent on building the dependencies when i am creating a docker image. (I have to use ldc for ARM, which is slower.) Is there an easy way to fetch and prebuild a dub package dependencies? something like "dub fetch-and-build vibe-d --recursive --cache=system"
DConf registration confirmation
Have you received registration confirmation after registering via PayPal? I'm asking because the payment links are on an unsecured page, and the credit card transaction was first refused because of potential fraud, so I had to make a call to make it happen.
Re: Opportunity: Software Execution Time Determinism
I think the problem can be separated into two: 1. Guarantee a given Big O complexity of a function, (that's what matters for most cases), 2. Guarantee / tell the worst case execution time / CPU cycles of a given @constanttime function. Combining these two, we can calculate the worst case execition time for the full program. @constanttime can have branches, each branch with different worst case execution time, it won't change the @constanttime nature of the funcion. (But makes it harder to calculate the worst case execution time, and the average case and the worst case won't be the same.) @constanttime could also have loops / recursion, if the number of iterations / recursion is limited. I.e. sorting 5 numbers during the median of 5 algorithm is @constanttime, even if it calls a sort function which is O(N log N). I.e. this is valid: @constanttime auto sort5(Range)(Range values) { assert(values.length <= 5); return values.bubblesort(); } /* inferred: @quadratic */ int[] bubblesort(int[] values) { for (int i=0; i
Re: emit: generalizes map, filter, joiner [proposal + implementation]
On Wednesday, 23 March 2016 at 17:29:55 UTC, Nick Treleaven wrote: On Monday, 21 March 2016 at 23:09:27 UTC, Tamas wrote: On Monday, 21 March 2016 at 11:48:52 UTC, Seb wrote: Could you try to point out whats wrong with map & filter? It's hard to do stuff like this: assert(9.iota.emit!(int,(put,a){if(a%2) put(a*a); if(a%3==0) put(a);}).equal([1,9,3,25,6,49])); Seems doable: mapFilter!((a){if(a%2) return some(a*a); if(a%3==0) return some(a); return none;}) This one emits only 1 element when a==3. (BTW what is `mapFilter` and `some`?)
Re: emit: generalizes map, filter, joiner [proposal + implementation]
On Monday, 21 March 2016 at 11:48:52 UTC, Seb wrote: Could you try to point out whats wrong with map & filter? It's hard to do stuff like this: assert(9.iota.emit!(int,(put,a){if(a%2) put(a*a); if(a%3==0) put(a);}).equal([1,9,3,25,6,49]));
Re: std.range.chunks with only an InputRange
I just run into this. Would be nice to have this! There's no reason why chunks should only work on ForwardRanges.
Re: Warning: statement is not reachable
On Wednesday, 2 March 2016 at 09:37:03 UTC, Johan Engelen wrote: On Wednesday, 2 March 2016 at 07:42:09 UTC, Tamas wrote: Thanks, fixing this single issue solved the compiler crash too. Did the compiler crash? Or just exit? (a crash would still be a bug) Crashed, just like in the case of Edwin's linked github issue: https://github.com/BlackEdder/painlessjson/issues/49 dmd failed with exit code 1. The minimized code in the OP does not crashes the compiler though.
Re: Warning: statement is not reachable
Thanks, fixing this single issue solved the compiler crash too. Thanks also for the tip using hasUDA! Works nicely!
Warning: statement is not reachable
My d code doesn't compile using ldc2 1.0.0-alpha or anything above DMD v2.068.0 Using these compilers I get a lot of "Warning: statement is not reachable". Then the both compiler crashes. I minimized the code to get the same warning, although the compilers do not crash this time, so this might not be the real culprit. Any suggestion how to fix this? Thanks! ldc2 -w reach.d dmd -w reach.d reach.d: struct Tag {} template isTagged(S) { enum bool isTagged = delegate() { foreach(attr; __traits(getAttributes, S)) { static if (is(attr == Tag)) { return true; } } return false; }(); } void main() { static @Tag struct MyStruct {} static struct VanillaStruct {} static assert(isTagged!MyStruct); static assert(!isTagged!VanillaStruct); }
Re: Virtual value types during compile-time for static type safety, static optimizations and function overloading.
Sorry, the main function of positive0.d correctly looks like this: int main() { return !((abs(-16) == 16) (abs(3) == 3) (square(5).absPositive == 25) (square(-4).absPositive == 16)); } But this does not affect the results, the asm file sizs or the asm abs function bodies.
Re: Virtual value types during compile-time for static type safety, static optimizations and function overloading.
On Saturday, 18 July 2015 at 13:16:26 UTC, Adam D. Ruppe wrote: On Saturday, 18 July 2015 at 10:06:07 UTC, Tamas wrote: Compile execute: $ dmd positive0.d; ./positive0; echo $? $ ldc2 positive0.d; ./positive0; echo $? Try adding the automatic optimize flags in all your cases. For dmd, `-O -inline`. Not sure about ldc but I think it is `-O` as well. Thanks, indeed, after -O -inline the bodies of the two abs functions are the same! :) The asm code of the templated version is still longer overall, but I think it's only some garbage that is not really executed. (e.g some with assert and unittest in the name, although I have none such) Soo thank you, it's really awesome! :)
Re: Virtual value types during compile-time for static type safety, static optimizations and function overloading.
I made a thorough comparison using multiple compilers and a summary of the findings. In short, there is a runtime overhead. I reduced the code to cut out the imports and made two versions with equivalent semantic content. positive0.d contains the hand written specializations of the abs function. positive.d contains the solution with function templates / static type analysis. /// /* positive0.d: Compile execute: $ dmd positive0.d; ./positive0; echo $? $ ldc2 positive0.d; ./positive0; echo $? generate ASM source: $ dmd positive0.d; gobjdump -d positive0.o positive0.dmd.s $ ldc2 positive0.d -output-s */ int absPositive(int n) { return n; } int abs(int n) { return (n=0) ? n : -n; } int square(int x) { return x * x; } int main() { return !((abs(-16) == 16) (abs(3) == 3) (square(5).abs == 25) (square(-4).abs == 16)); } /// /* positive.d: Compile execute: $ dmd positive.d; ./positive; echo $? $ ldc2 positive.d; ./positive; echo $? generate ASM source: $ dmd positive.d; gobjdump -d positive.o positive.dmd.s $ ldc2 positive.d -output-s */ struct Positive { int num; alias num this; } Positive abs(T)(T n) { static if (is(T == Positive)) { return n; } else { return Positive((n = 0) ? n : -n); } } Positive square(int x) { return Positive(x * x); } int main() { return !((abs(-16) == 16) (abs(3) == 3) (square(5).abs == 25) (square(-4).abs == 16)); } /// I compared the generated asms. The asm code was substantially longer in case of non-hand written specializations of the abs function. The 'optimized' versions of the abs function were equivalent, but the 'non-optimzed' versions shows the runtime overhead for dmd and ldc2 as well, a double 'mov' commands instead of a single ones; The compiled hand written code was roughly half the size for both compilers: File sizes: ldc: 2678 positive0.s 4313 positive.s dmd: 3442 positive0.dmd.s 8701 positive.dmd.s You can see the abs functions below, and you can spot the double 'mov' operations: positive.dmd.s: 0230 _D8positive10__T3absTiZ3absFNaNbNiNfiZS8positive8Positive: 230: 55 push %rbp 231: 48 8b ecmov%rsp,%rbp 234: 48 83 ec 10 sub$0x10,%rsp 238: 85 ff test %edi,%edi 23a: 78 02 js 23e _D8positive10__T3absTiZ3absFNaNbNiNfiZS8positive8Positive+0xe 23c: eb 02 jmp240 _D8positive10__T3absTiZ3absFNaNbNiNfiZS8positive8Positive+0x10 23e: f7 df neg%edi 240: 89 7d f0mov%edi,-0x10(%rbp) 243: 48 89 f8mov%rdi,%rax 246: c9 leaveq 247: c3 retq 0248 _D8positive28__T3absTS8positive8PositiveZ3absFNaNbNiNfS8positive8PositiveZS8positive8Positive: 248: 55 push %rbp 249: 48 8b ecmov%rsp,%rbp 24c: 48 83 ec 10 sub$0x10,%rsp 250: 48 89 f8mov%rdi,%rax 253: c9 leaveq 254: c3 retq 255: 0f 1f 00nopl (%rax) positive0.dmd.s: 00a0 _D9positive011absPositiveFiZi: a0: 55 push %rbp a1: 48 8b ecmov%rsp,%rbp a4: 48 83 ec 10 sub$0x10,%rsp a8: 48 89 f8mov%rdi,%rax ab: c9 leaveq ac: c3 retq ad: 0f 1f 00nopl (%rax) 00b0 _D9positive03absFiZi: b0: 55 push %rbp b1: 48 8b ecmov%rsp,%rbp b4: 48 83 ec 10 sub$0x10,%rsp b8: 85 ff test %edi,%edi ba: 78 05 js c1 _D9positive03absFiZi+0x11 bc: 48 89 f8mov%rdi,%rax bf: eb 05 jmpc6 _D9positive03absFiZi+0x16 c1: 48 89 f8mov%rdi,%rax c4: f7 d8 neg%eax c6: c9 leaveq c7: c3 retq ldc2: positive.s: __D8positive10__T3absTiZ3absFNaNbNiNfiZS8positive8Positive: .cfi_startproc movl%edi, -4(%rsp) cmpl$0, -4(%rsp) jl LBB2_2 leaq-4(%rsp), %rax movq%rax, -16(%rsp) jmp LBB2_3 LBB2_2: leaq-20(%rsp), %rax xorl%ecx, %ecx subl-4(%rsp), %ecx movl%ecx, -20(%rsp) movq%rax, -16(%rsp) LBB2_3: movq-16(%rsp), %rax movl(%rax), %ecx movl%ecx, -8(%rsp) movl%ecx, %eax retq .cfi_endproc .globl __D8positive28__T3absTS8positive8PositiveZ3absFNaNbNiNfS8positive8PositiveZS8positive8Positive .weak_definition
Re: String Metaprogramming
Thanks Nicholas , I have integrated some of your advice on the edited code i.e. foreach and ref in pattern . Hope I fully understood what you meant. Am yet to look whether I still need to change the signature . I have heared there are two approaches to this, Where does one really draw the line between CTFE and Template metaprogramming? Template metaprogramming == abuse the template facility in C++ to run a program in compile time used to be the only way to execute something at compile time in C++. In D you don't want to do that as writing such code is a matter of putting an enum or static at the right place. Still, you can use templates to achieve your goal, if that helps.
Re: Virtual value types during compile-time for static type safety, static optimizations and function overloading.
On Friday, 17 July 2015 at 23:16:51 UTC, ZombineDev wrote: On Friday, 17 July 2015 at 23:15:31 UTC, ZombineDev wrote: On Friday, 17 July 2015 at 21:20:41 UTC, Tamas wrote: Is there a solution that results the same static optimizations, but has no runtime penalty, i.e. the functions just operates with ints? (At least when compiled) Did you try looking at assembly generated by GDC or LDC with full optimizations? For example GDC does quite better than DMD for the proposed SafeInt type: https://github.com/D-Programming-Language/phobos/pull/3389#issuecomment-119005595 Also, see the table at the bottom of this comment: https://github.com/D-Programming-Language/phobos/pull/3389#issuecomment-117450524 Thanks for the pointers! My first priority a performant library, secondary is a nice api, 3rd is a nice implementation. So that kind of rules put Amy degradation compared to ints. I used DMD, BTW. I see no reason for the necessity of performance degradation. Essentially I just want to assign a similar qualifyer like const or immutable. They are checked and used at compile time, but erased for runtime. Same here.
Virtual value types during compile-time for static type safety, static optimizations and function overloading.
I got inspired by Andrei's Generic Programming Must Go talk: https://www.youtube.com/watch?v=mCrVYYlFTrA I.e. writing functions with static if-s, based on what we know about the input. So the question is how to annotate the input variables? Adam showed an excellent solution for this, by wrapping the value into a struct, and using alias: http://stackoverflow.com/questions/31442059/virtual-static-value-types Unfortunately, it's not without runtime penalty. I have checked this idea with ints, against the generated asm.dlang.org code. Unfortunately the struct wrapper results in longer asm code. In theory such run-time penalty is not necessary, as everything is available compile-time. To understand my use-case, here is an example math library that skips certain validations or computations altogether, whether some properties of the input can be inferred from how the value was produced: import std.math : sqrt; import std.conv; struct Positive { int num; alias num this; } Positive abs(T)(T n) { static if (is(T == Positive)) { return n; } if (n = 0) return Positive(n); return Positive(-n); } Positive isqrt(T)(T x) { static if (is(T == Positive)) { return Positive(sqrt(x.to!float).to!int); } if (x0) { throw new Exception(no root for negative numbers); } return Positive(sqrt(x.to!float).to!int); } unittest { assert(abs(-4) == 4); // full abs runs assert(isqrt(4).abs() == 2); // full isqrt runs, abs returns n immediately. assert(abs(-4).isqrt() == 2); // full abs runs, isqrt return immediately, skipping validation; } Although this code is fully operational, presents nice api and compile-time optimizations, the extra Struct wrapper is not without runtime penalty. Is there a solution that results the same static optimizations, but has no runtime penalty, i.e. the functions just operates with ints? (At least when compiled) Thanks, Tamas