{"id":2717,"date":"2020-09-28T13:38:14","date_gmt":"2020-09-28T13:38:14","guid":{"rendered":"https:\/\/dlang.org\/blog\/?p=2717"},"modified":"2021-09-30T13:30:15","modified_gmt":"2021-09-30T13:30:15","slug":"function-generation-in-d-the-good-the-bad-the-ugly-and-the-bolt","status":"publish","type":"post","link":"https:\/\/dlang.org\/blog\/2020\/09\/28\/function-generation-in-d-the-good-the-bad-the-ugly-and-the-bolt\/","title":{"rendered":"Function Generation in D: The Good, the Bad, the Ugly, and the Bolt"},"content":{"rendered":"<h2 id=\"introduction\">Introduction<\/h2>\n<p><img loading=\"lazy\" src=\"https:\/\/dlang.org\/blog\/wp-content\/uploads\/2016\/08\/d6.png\" alt=\"Digital Mars D logo\" width=\"200\" height=\"200\" class=\"alignright size-full wp-image-181\" \/><\/p>\n<p>A while ago, Andrei Alexandrescu started a thread in the D Programming Language forums, <a href=\"https:\/\/forum.dlang.org\/post\/rfim9h$a45$1@digitalmars.com\">titled &#8220;Perfect forwarding&#8221;<\/a>, about a challenge which came up during <a href=\"https:\/\/forum.dlang.org\/thread\/reah5u$dua$1@digitalmars.com\">the July 2020 beerconf<\/a>:<\/p>\n<blockquote><p>\nWrite an idiomatic template <code>forward<\/code> that takes an alias <code>fun<\/code> and defines (generates) one overload for each overload of <code>fun<\/code>.\n<\/p><\/blockquote>\n<p>Several people proposed solutions. In the course of the discussion, it arose that there is sometimes a need to alter a function&#8217;s properties, like adding, removing, or hanging user-defined attributes or parameter storage classes. This was exactly the problem I struggled with while trying to support all the bells and whistles of D functions in my <code>openmethods<\/code> library.<\/p>\n<p>Eventually, I created a module that helps with this problem and contributed it to the <a href=\"https:\/\/aliak00.github.io\/bolts\/bolts.html\">bolts meta-programming library<\/a>. But before we get to that, let&#8217;s first take a closer look at function generation in D.<\/p>\n<h2 id=\"thegood\">The Good<\/h2>\n<p>I speculate that many a programmer who is a moderately advanced beginner in D would quickly come up with a mostly correct solution to the &#8220;Perfect forwarding&#8221; challenge, especially those with a C++ background who have an interest in performing all sorts of magic tricks by means of template meta-programming. The solution will probably look like this:<\/p>\n<pre class=\"prettyprint lang-d\">template forward(alias fun)\r\n{\r\n  import std.traits: Parameters;\r\n  static foreach (\r\n    ovl; __traits(getOverloads, __traits(parent, fun), __traits(identifier, fun))) {\r\n    auto forward(Parameters!ovl args)\r\n    {\r\n      return ovl(args);\r\n    }\r\n  }\r\n}\r\n\r\n...\r\n\r\nint plus(int a, int b) { return a + b; }\r\nstring plus(string a, string b) { return a ~ b; }\r\n\r\nassert(forward!plus(1, 2) == 3);        \/\/ pass\r\nassert(forward!plus(&quot;a&quot;, &quot;b&quot;) == &quot;ab&quot;); \/\/ pass<\/pre>\n<p>This solution is not perfect, as we shall see, but it is not far off either. It covers many cases, including some that a beginner may not even be aware of. For example, <code>forward<\/code> handles the following function without dropping function attributes or parameter storage classes:<\/p>\n<pre class=\"prettyprint lang-d\">class Matrix { ... }\r\n\r\nMatrix times(scope const Matrix a, scope const Matrix b) pure @safe\r\n{\r\n  return ...;\r\n}\r\n\r\npragma(msg, typeof(times));\r\n\/\/ pure @safe Matrix(scope const(Matrix) a, scope const(Matrix) b)\r\n\r\npragma(msg, typeof(forward!times));\r\n\/\/ pure @safe Matrix(scope const(Matrix) _param_0, scope const(Matrix) _param_1)<\/pre>\n<p>It even handles <a href=\"https:\/\/dlang.org\/spec\/attribute.html#uda\">user-defined attributes (UDAs)<\/a> on parameters:<\/p>\n<pre class=\"prettyprint lang-d\">struct testParameter;\r\n\r\nvoid testPlus(@testParameter int a, @testParameter int b);\r\n\r\npragma(msg, typeof(testPlus));\r\n\/\/ void(@(testParameter) int a, @(testParameter) int b)\r\n\r\npragma(msg, typeof(forward!testPlus));\r\n\/\/ void(@(testParameter) int a, @(testParameter) int b)<\/pre>\n<p>Speaking of UDAs, that&#8217;s one of the issues with the solution above: it doesn&#8217;t carry <em>function<\/em> UDAs. It also doesn&#8217;t work with functions that return a reference. Both issues are easy to fix:<\/p>\n<pre class=\"prettyprint lang-d\">template forward(alias fun)\r\n{\r\n  import std.traits: Parameters;\r\n  static foreach (ovl; __traits(getOverloads, __traits(parent, fun), __traits(identifier, fun)))\r\n  {\r\n    @(__traits(getAttributes, fun)) \/\/ copy function UDAs\r\n    auto ref forward(Parameters!ovl args)\r\n    {\r\n      return ovl(args);\r\n    }\r\n  }\r\n}<\/pre>\n<p>This solution is still not 100% correct though. If the forwardee is <code>@trusted<\/code>, the forwarder will be <code>@safe<\/code>:<\/p>\n<pre class=\"prettyprint lang-d\">@trusted void useSysCall() { ... }\r\n\r\npragma(msg, typeof(&amp;useSysCall));         \/\/ void function() @trusted\r\npragma(msg, typeof(&amp;forward!useSysCall)); \/\/ void function() @safe<\/pre>\n<p>This happens because the body of the forwarder consists of a single statement calling the <code>useSysCall<\/code> function. Since calling a trusted function is safe, the forwarder is <a href=\"https:\/\/dlang.org\/spec\/function.html#function-attribute-inference\">automatically deemed safe<\/a> by the compiler.<\/p>\n<h2 id=\"thebad\">The Bad<\/h2>\n<p>However, Andrei&#8217;s challenge was not exactly what we discussed in the previous section. It came with a bit of pseudocode that suggested the template <a href=\"https:\/\/dlang.org\/spec\/template.html#implicit_template_properties\">should not be eponymous<\/a>. In other words, I believe that the exact task was to write a template that would be used like this: <code>forward!fun.fun(...)<\/code>. Here is the pseudocode:<\/p>\n<pre class=\"prettyprint lang-d\">\/\/ the instantiation of forward!myfun would be (stylized):\r\n\r\ntemplate forward!myfun\r\n{\r\n    void myfun(int a, ref double b, out string c)\r\n    {\r\n        return myfun(a, b, c);\r\n    }\r\n    int myfun(in string a, inout double b)\r\n    {\r\n        return myfun(a, b);\r\n    }\r\n}<\/pre>\n<p>Though this looks like a small difference, if we want to implement exactly this, a complication arises. In the eponymous <code>forward<\/code>, we did not need to create a new identifier; we simply used the template name as the function name. Thus, the function name was fixed. Now we need to create a function with a name that depends on the forwardee&#8217;s name. And the only way to do this is <a href=\"https:\/\/dlang.org\/spec\/statement.html#mixin-statement\">with a string mixin<\/a>.<\/p>\n<p>The first time I had to do this, I tried the following:<\/p>\n<pre class=\"prettyprint lang-d\">template forward(alias fun)\r\n{\r\n  import std.format : format;\r\n  import std.traits: Parameters;\r\n  enum name = __traits(identifier, fun);\r\n  static foreach (ovl; __traits(getOverloads, __traits(parent, fun), name)) {\r\n    @(__traits(getAttributes, fun))\r\n    auto ref mixin(name)(Parameters!ovl args)\r\n    {\r\n      return ovl(args);\r\n    }\r\n  }\r\n}<\/pre>\n<p>This doesn&#8217;t work because a string mixin can only be used to create expressions or statements. Therefore, the solution is to simply expand the mixin to encompass the entire function definition. The token-quote operator <code>q{}<\/code> is very handy for this:<\/p>\n<pre class=\"prettyprint lang-d\">template forward(alias fun)\r\n{\r\n  import std.format : format;\r\n  import std.traits: Parameters;\r\n  enum name = __traits(identifier, fun);\r\n  static foreach (ovl; __traits(getOverloads, __traits(parent, fun), name)) {\r\n    mixin(q{\r\n        @(__traits(getAttributes, fun))\r\n          auto ref %s(Parameters!ovl args)\r\n        {\r\n          return ovl(args);\r\n        }\r\n      }.format(name));\r\n  }\r\n}<\/pre>\n<p>Though string mixins are powerful, they are essentially C macros. For many D programmers, resorting to a string mixin can feel like a defeat.<\/p>\n<p>Let us now move on to a similar, yet significantly more difficult, challenge:<\/p>\n<blockquote>\n<p>Write a class template that mocks an interface.<\/p>\n<\/blockquote>\n<p>For example:<\/p>\n<pre class=\"prettyprint lang-d\">interface JsonSerializable\r\n{\r\n  string asJson() const;\r\n}\r\n\r\nvoid main()\r\n{\r\n  auto mock = new Mock!JsonSerializable();\r\n}<\/pre>\n<p>Extrapolating the techniques acquired during the previous challenge, a beginner would probably try this first:<\/p>\n<pre class=\"prettyprint lang-d\">class Mock(alias Interface) : Interface\r\n{\r\n  import std.format : format;\r\n  import std.traits: Parameters;\r\n  static foreach (member; __traits(allMembers, Interface)) {\r\n    static foreach (fun; __traits(getOverloads, Interface, member)) {\r\n      mixin(q{\r\n          @(__traits(getAttributes, fun))\r\n          auto ref %s(Parameters!fun args)\r\n          {\r\n            \/\/ record call\r\n            static if (!is(ReturnType!fun == void)) {\r\n              return ReturnType!fun.init;\r\n            }\r\n          }\r\n        }.format(member));\r\n    }\r\n  }\r\n}<\/pre>\n<p>Alas, this fails to compile, throwing errors like:<\/p>\n<pre>Error: function `challenge.Mock!(JsonSerializable).Mock.asJson` return type\r\ninference is not supported if may override base class function<\/pre>\n<p>In other words, <code>auto<\/code> cannot be used here. We have to fall back to explicitly specifying the return type:<\/p>\n<pre class=\"prettyprint lang-d\">class Mock(alias Interface) : Interface\r\n{\r\n  import std.format : format;\r\n  import std.traits: Parameters, ReturnType;\r\n  static foreach (member; __traits(allMembers, Interface)) {\r\n    static foreach (fun; __traits(getOverloads, Interface, member)) {\r\n      mixin(q{\r\n          @(__traits(getAttributes, fun))\r\n          ReturnType!fun %s(Parameters!fun args)\r\n          {\r\n            \/\/ record call\r\n            static if (!is(ReturnType!fun == void)) {\r\n              return ReturnType!fun.init;\r\n            }\r\n          }\r\n        }.format(member));\r\n    }\r\n  }\r\n}<\/pre>\n<p>This will not handle <code>ref<\/code> functions though. What about adding a <code>ref<\/code> in front of the return type, like we did in the first challenge?<\/p>\n<pre class=\"prettyprint lang-d\">\/\/ as before\r\n          ref ReturnType!fun %s(Parameters!fun args) ...<\/pre>\n<p>This will fail with all the functions in the interface that do <em>not<\/em> return a reference.<\/p>\n<p>The reason why everything worked almost magically in the first challenge is that we called the wrapped function inside the template. It enabled the compiler to deduce almost all of the characteristics of the original function and copy them to the forwarder function. But we have no model to copy from here. The compiler will copy <em>some<\/em> of the aspects of the function (<code>pure<\/code>, <code>@safe<\/code>, etc.) to match those of the overriden function, but not some others (<code>ref<\/code>, <code>const<\/code>, and the other modifiers).<\/p>\n<p>Then, there is the issue of the function modifiers: <code>const<\/code>, <code>immutable<\/code>, <code>shared<\/code>, and <code>static<\/code>. These are yet another category of function &#8220;aspects&#8221;.<\/p>\n<p>At this point, there is no other option than to analyze some of the function attributes by means of traits, and convert them to a string to be injected in the string mixin:<\/p>\n<pre class=\"prettyprint lang-d\">      mixin(q{\r\n          @(__traits(getAttributes, fun))\r\n          %sReturnType!fun %s(Parameters!fun args)\r\n          {\r\n            \/\/ record call\r\n            static if (!is(ReturnType!fun == void)) {\r\n              return ReturnType!fun.init;\r\n            }\r\n          }\r\n        }.format(\r\n            (functionAttributes!fun &amp; FunctionAttribute.const_ ? &quot;const &quot; : &quot;&quot;)\r\n          ~ (functionAttributes!fun &amp; FunctionAttribute.ref_ ? &quot;ref &quot; : &quot;&quot;)\r\n          ~ ...,\r\n          member));\r\n    }<\/pre>\n<p>If you look at the implementation of <code>std.typecons.wrap<\/code>, you will see that part of the code deals with synthesizing bits of a string mixin for the storage classes and modifiers.<\/p>\n<h2 id=\"theugly\">The Ugly<\/h2>\n<p>So far, we have looked at the function storage classes, modifiers, and UDAs, but we have merely passed the parameter list as a single, monolithic block. However, sometimes we need to perform adjustments to the parameter list of the generated function. This may seem far-fetched, but it does happen. I encountered this problem in my <code>openmethods<\/code> library. During the &#8220;Perfect forwarding&#8221; discussion, it appeared that I was not the only one who wanted to do this.<\/p>\n<p>I won&#8217;t delve into the details of <code>openmethods<\/code> here (see <a href=\"https:\/\/dlang.org\/blog\/2017\/08\/28\/open-methods-from-c-to-d\/\">an older blog post<\/a> for an overview of the module); for the purpose of this article, it suffices to say that, given a function declaration like this one:<\/p>\n<pre class=\"prettyprint lang-d\">Matrix times(virtual!Matrix a, double b);<\/pre>\n<p><code>openmethods<\/code> generates this function:<\/p>\n<pre class=\"prettyprint lang-d\">Matrix dispatcher(Matrix a, double b)\r\n{\r\n  return resolve(a)(a, b);\r\n}<\/pre>\n<p>The <code>virtual<\/code> template is a marker; it indicates which parameters should be taken into account (i.e., passed to <code>resolve<\/code>) when picking the appropriate specialization of <code>times<\/code>. Note that only <code>a<\/code> is passed to the <code>resolve<\/code> function&#8212;that is because the first parameter uses the <code>virtual!<\/code> marker and the second does not.<\/p>\n<p>Bear in mind, though, that <code>dispatcher<\/code> is not allowed to use the type of the parameters directly. Inside the <code>openmethods<\/code> module, there is no <code>Matrix<\/code> type. Thus, when <code>openmethods<\/code> is handed a function declaration, it needs to synthesize a <code>dispatcher<\/code> function that refers to the declaration&#8217;s parameter types exclusively <em>via<\/em> the declaration. In other words, it needs to use the <code>ReturnType<\/code> and <code>Parameters<\/code> <a href=\"https:\/\/dlang.org\/phobos\/std_traits.html\">templates from <code>std.traits<\/code><\/a> to extract the types involved in the declaration &#8211; just like we did in the examples above.<\/p>\n<p>Let&#8217;s put aside function attributes and UDAs &#8211; we already discussed those in the previous section. The obvious solution then seems to be:<\/p>\n<pre class=\"prettyprint lang-d\">ReturnType!times dispatcher(\r\n  RemoveVirtual!(Parameters!times[0]) a, Parameters!times[1] b)\r\n{\r\n  return resolve(a)(a, b);\r\n}\r\n\r\npragma(msg, typeof(&amp;dispatcher)); \/\/ Matrix function(Matrix, double)<\/pre>\n<p>where <code>RemoveVirtual<\/code> is a simple template that peels off the <code>virtual!<\/code> marker from the type.<\/p>\n<p>Does this preserve <em>parameter<\/em> storage classes and UDAs? Unfortunately, it does not:<\/p>\n<pre class=\"prettyprint lang-d\">@nogc void scale(ref virtual!Matrix m, lazy double by);\r\n\r\n@nogc ReturnType!scale dispatcher(RemoveVirtual!(Parameters!scale[0]) a, Parameters!scale[1] b)\r\n{\r\n  return resolve(a)(a, b);\r\n}\r\n\r\npragma(msg, typeof(&amp;dispatcher)); \/\/ void function(Matrix a, double b)<\/pre>\n<p>We lost the <code>ref<\/code> on the first parameter and the <code>lazy<\/code> on the second. What happened to them?<\/p>\n<p>The culprit is <code>Parameters<\/code>. This template is a wrapper around an obscure feature <a href=\"https:\/\/dlang.org\/spec\/expression.html#is_expression\">of the <code>is<\/code><\/a> operator used in conjunction with the <code>__parameters<\/code> type specialization. And it is quite a strange beast. We used it above to copy the parameter list of a function, as a whole, to another function, and it worked perfectly. The problem is what happens when you try to process the parameters separately. Let&#8217;s look at a few examples:<\/p>\n<pre class=\"prettyprint lang-d\">pragma(msg, Parameters!scale.stringof); \/\/ (ref virtual!(Matrix), lazy double)\r\npragma(msg, Parameters!scale[0].stringof); \/\/ virtual!(Matrix)\r\npragma(msg, Parameters!scale[1].stringof); \/\/ double<\/pre>\n<p>We see that accessing a parameter individually returns the type&#8230; and discards everything else!<\/p>\n<p>There is actually a way to extract everything about a single parameter: use a <em>slice<\/em> instead of an element of the paramneter pack (yes, this is getting strange):<\/p>\n<pre class=\"prettyprint lang-d\">pragma(msg, Parameters!scale[0..1].stringof); \/\/ (ref virtual!(Matrix))\r\npragma(msg, Parameters!scale[1..2].stringof); \/\/ (lazy double)<\/pre>\n<p>So this gives us a solution for handling the second parameter of <code>scale<\/code>:<\/p>\n<pre class=\"prettyprint lang-d\">ReturnType!scale dispatcher(???, Parameters!scale[1..2]) { ... }<\/pre>\n<p>But what can we put in place of <code>???<\/code>. <code>RemoveVirtual!(Parameters!scale[0..1])<\/code> would not work. <code>RemoveVirtual<\/code> expects a type, and <code>Parameters!scale[1..2]<\/code> is not a type&#8212;it is a sort of conglomerate that contains a type, and perhaps storage classes, type constructors, and UDAs.<\/p>\n<p>At this point, we have no other choice but to construct a string mixin once again. Something like this:<\/p>\n<pre class=\"prettyprint lang-d\">mixin(q{\r\n    %s ReturnType!(scale) dispatcher(\r\n      %s RemoveVirtual!(Parameters!(scale)[1]) a,\r\n      Parameters!(scale)[1..2] b)\r\n    {\r\n        resolve(a)(a, b);\r\n    }\r\n  }.format(\r\n    functionAttributes!scale &amp; FunctionAttribute.nogc ? &quot;@nogc &quot; : &quot;&quot;\r\n    \/* also handle other function attributes *\/,\r\n    __traits(getParameterStorageClasses, scale, 0)));\r\n\r\npragma(msg, typeof(dispatcher)); \/\/ @nogc void(ref double a, lazy double)<\/pre>\n<p>This is not quite sufficient though, because it still doesn&#8217;t take care of parameter UDAs.<\/p>\n<h3 id=\"toboltlyrefract...\">To Boltly Refract&#8230;<\/h3>\n<p><code>openmethods<\/code> once contained kilometers of mixin code like the above. Such heavy use of string mixins was too ugly and messy, so much so that the project began to feel less like fun and more like work. So I decided to sweep all the ugliness under a neat interface, once and for all. The result was a &#8220;refraction&#8221; module, which I later carved out of <code>openmethods<\/code> and donated to <a href=\"https:\/\/github.com\/aliak00\/bolts\">Ali Akhtarzada&#8217;s excellent <code>bolts<\/code> library<\/a>. <code>bolts<\/code> attempts to fill in the gaps and bring some regularity to D&#8217;s motley set of meta-programming features.<\/p>\n<p><code>refraction<\/code>&#8217;s entry point is the <code>refract<\/code> function template. It takes a function and an &#8220;anchor&#8221; string, and returns an immutable <code>Function<\/code> object that captures all the aspects of a function. <code>Function<\/code> objects can be used at compile-time. It is, actually, their <em>raison d&#8217;\u00eatre<\/em>.<\/p>\n<p><code>Function<\/code> has a <code>mixture<\/code> property that returns a declaration for the original function. For example:<\/p>\n<pre class=\"prettyprint lang-d\">Matrix times(virtual!Matrix a, double b);\r\npragma(msg, refract!(times, &quot;times&quot;).mixture);\r\n\/\/ @system ReturnType!(times) times(Parameters!(times) _0);<\/pre>\n<p>Why does <code>refract<\/code> need the anchor string? Can&#8217;t the string <code>&quot;times&quot;<\/code> be inferred from the function by means of <code>__traits(identifier...)<\/code>? Yes, it can, but in real applications we don&#8217;t want to use this. The whole point of the library is to be used in templates, where the function is typically passed to <code>refract<\/code> via an alias. In general, the function&#8217;s name has no meaning in the template&#8217;s scope&#8212;or if, by chance, the name exists, it does not name the function. All the meta-expressions used to dissect the function must work in terms of the <em>local<\/em> symbol that identifies the alias.<\/p>\n<p>Consider:<\/p>\n<pre class=\"prettyprint lang-d\">module matrix;\r\n\r\nMatrix times(virtual!Matrix a, double b);\r\n\r\nMethod!times timesMethod; \/\/ openmethods creates a `Method` object for each\r\n                          \/\/ declared method\r\n\r\nmodule openmethods;\r\n\r\nstruct Method(alias fun)\r\n{\r\n    enum returnTypeMixture = refract!(fun, &quot;fun&quot;).returnType;\r\n    pragma(msg, returnTypeMixture);              \/\/ ReturnType!(fun)\r\n    mixin(&quot;alias R = &quot;, returnTypeMixture, &quot;;&quot;); \/\/ ok\r\n    pragma(msg, R.stringof);                     \/\/ Matrix\r\n}<\/pre>\n<p>There is no <code>times<\/code> and no <code>Matrix<\/code> in <code>module openmethods<\/code>. Even if they existed, they could <em>not<\/em> be the <code>times<\/code> function and the <code>Matrix<\/code> class from <code>module matrix<\/code>, as this would require a circular dependency between the two modules, something that D forbids by default. However, there is a <code>fun<\/code> symbol, and it aliases to the function; thus, the return type can be expressed as <code>ReturnType!(fun)<\/code>.<\/p>\n<p>All aspects of the function are available piecemeal. For example:<\/p>\n<pre class=\"prettyprint lang-d\">@nogc void scale(ref virtual!Matrix m, lazy double by);\r\npragma(msg, refract!(scale, &quot;scale&quot;).parameters[0].storageClasses); \/\/ [&quot;ref&quot;]<\/pre>\n<p><code>Function<\/code> also has methods that return a new <code>Function<\/code> object, with an alteration to one of the aspects. They can be used to create a variation of a function. For example:<\/p>\n<pre class=\"prettyprint lang-d\">pragma(msg,\r\n  refract!(scale, &quot;scale&quot;)\r\n  .withName(&quot;dispatcher&quot;)\r\n  .withBody(q{{ resolve(_0[0])(_0); }})\r\n  .mixture\r\n);\r\n\r\n@nogc @system ReturnType!(scale) dispatcher(ref Parameters!(scale)[0] _0, lazy Parameters!(scale)[1] _1)\r\n{\r\n  resolve(_0[0])(_0);\r\n}<\/pre>\n<p>This is the reason behind the name &#8220;refraction&#8221;: the module creates a blueprint of a function, performs some alterations on it, and returns a string&#8212;called a mixture&#8212;which, when passed to <code>mixin<\/code>, will create a new function.<\/p>\n<p><code>openmethods<\/code> needs to change the type of the first parameter while preserving storage classes. With <code>bolts.experimental.refraction<\/code>, this becomes easy:<\/p>\n<pre class=\"prettyprint lang-d\">original = refract!(scale, &quot;scale&quot;);\r\n\r\npragma(msg,\r\n  original\r\n  .withName(&quot;dispatcher&quot;)\r\n  .withParameters(\r\n    [original.parameters[0].withType(\r\n        &quot;RemoveVirtual!(%s)&quot;.format(original.parameters[0].type)),\r\n     original.parameters[1],\r\n    ])\r\n  .withBody(q{{\r\n      return resolve(_0)(%s);\r\n   }}.format(original.argumentMixture))\r\n);<\/pre>\n<p>This time, the generated code splits the parameter pack into individual components:<\/p>\n<pre class=\"prettyprint lang-d\">@nogc @system ReturnType!(scale) dispatcher(\r\n  ref RemoveVirtual!(Parameters!(scale)[0]) _0, Parameters!(scale)[1..2] _1)\r\n{\r\n  return resolve(_0)(_0);\r\n}<\/pre>\n<p>Note how the first and second parameters are handled differently. The first parameter is cracked open because we need to replace the type. That forces us to access the first <code>Parameters<\/code> value via indexing, and that loses the storage classes, UDAs, etc. So they need to be re-applied explicitly.<\/p>\n<p>On the other hand, the second parameter does not have this problem. It is not edited; thus, the <code>Parameters<\/code> slice trick can be used. The <code>lazy<\/code> is indeed there, but it is inside the parameter conglomerate.<\/p>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>Initially, D looked almost as good as Lisp for generating functions. As we tried to gain finer control of the generated function, our code started to look a lot more like C macros; in fact, in some respects, it was even worse: we had to put an entire function definition in a string mixin just to set its name.<\/p>\n<p>This is due to the fact that D is not as &#8220;regular&#8221; a language as Lisp. Some of the people helming the evolution of D are working on changing this, and it is my hope that an improved D will emerge in the not-too-distant future.<\/p>\n<p>In the meantime, <a href=\"https:\/\/github.com\/aliak00\/bolts\/blob\/master\/source\/bolts\/experimental\/refraction.d\">the experimental refraction module<\/a> from the bolts meta-programming library offers a saner, easier way of generating functions without compromising on the idiosyncrasies that come with them. It allows you to pretend that functions can be disassembled and reassembled at will, while hiding all the gory details of the string mixins that are necessarily involved in that task.<\/p>\n<hr \/>\n<p><em>Jean-Louis Leroy is not French, but Belgian. He got his first taste of programming from a HP-25 calculator. His first real programming language was Forth, where CTFE is pervasive. Later he programmed (a little) in Lisp and Smalltalk, and (a lot) in C, C++, and Perl. He now works for Bloomberg LP in New York. His interests include object-relational mapping, open multi-methods, DSLs, and language extensions in general.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction A while ago, Andrei Alexandrescu started a thread in the D Programming Language forums, titled &#8220;Perfect forwarding&#8221;, about a challenge which came up during the July 2020 beerconf: Write an idiomatic template forward that takes an alias fun and defines (generates) one overload for each overload of fun. Several people proposed solutions. In the [&hellip;]<\/p>\n","protected":false},"author":23,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[43,26,9],"tags":[],"_links":{"self":[{"href":"https:\/\/dlang.org\/blog\/wp-json\/wp\/v2\/posts\/2717"}],"collection":[{"href":"https:\/\/dlang.org\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dlang.org\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dlang.org\/blog\/wp-json\/wp\/v2\/users\/23"}],"replies":[{"embeddable":true,"href":"https:\/\/dlang.org\/blog\/wp-json\/wp\/v2\/comments?post=2717"}],"version-history":[{"count":3,"href":"https:\/\/dlang.org\/blog\/wp-json\/wp\/v2\/posts\/2717\/revisions"}],"predecessor-version":[{"id":2721,"href":"https:\/\/dlang.org\/blog\/wp-json\/wp\/v2\/posts\/2717\/revisions\/2721"}],"wp:attachment":[{"href":"https:\/\/dlang.org\/blog\/wp-json\/wp\/v2\/media?parent=2717"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dlang.org\/blog\/wp-json\/wp\/v2\/categories?post=2717"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dlang.org\/blog\/wp-json\/wp\/v2\/tags?post=2717"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}