(Ab)Using Overload Sets to Create Ad-Hoc Template APIs in D

https://news.ycombinator.com/rss Hits: 1
Summary

“Overload set” is a term of art that seemingly arises from the reuse of overload rules across the years. Overload sets quietly power a lot of D’s generic programming, and once you understand them explicitly, a whole class of API design opens up. import std; void bar(int) { "int".writeln; } void bar(float) { "float".writeln; } void bar(bool) { "bool".writeln; } void useIt(alias F)() { F(1); // prints "int" F(13.37); // prints "float" F(true); // prints "bool" } unittest { useIt!bar; } What exactly is bar when passed to useIt? Wait, does it survive as useIt.F? (Yes, it compiles as is.) What Are Overload Sets? The specification: An Overload Set is the set of functions with the same name declared in the same scope that participate in overload resolution. And from the alias spec: Aliases can also ‘import’ a set of overloaded functions that can be overloaded with functions in the current scope… The behavior of overload sets is scattered across the spec. A few sentences here, a few more tucked away in the template section. Template specialization lets you pattern-match against the whole set; pick the right implementation based on compile-time arguments. Overload sets can work with several very different things. I use the following definition: An overload set is a collection of things that share a name and a closely related template header. You may not know everything that can be templatized, and real-world template usage is extremely concerned about making only one declaration match at a time. Specialization on Integer Values alias typeAt(int I : 0) = int; alias typeAt(int I : 1) = float; alias typeAt(int I : 2) = string; enum typeAtLength = Length!typeAt; template Length(alias A, int acc=0){ // returns the pseudo-length of an overloadset static if( ! __traits(compiles,A!acc) ){ enum Length=acc; } else { enum Length=Length!(A,acc+1); } } static foreach (i; 0 .. typeAtLength) { pragma(msg, typeAt!i.stringof); } // prints: int, float, string By treating value specialization ...

First seen: 2026-07-21 18:31

Last seen: 2026-07-21 18:31