Compile-Time Function Parameters That Aren't Types?

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Feb 24 06:18:02 UTC 2021


On Wed, Feb 24, 2021 at 03:52:57AM +0000, Kyle Ingraham via Digitalmars-d-learn wrote:
[...]
> I was under the impression that compile-time or template parameters
> were only for types.

In D, template parameters can take not only types, but almost any type
(provided they are constructible at compile-time).  Basically, D views
template parameters as *compile-time parameters*; i.e., they are treated
like ordinary parameters, except that they happen to be passed at
compile-time.


> [...] Why would one write a function this way?

Usually it's when there's a decision that needs to be made at
compile-time (or desirable to be made at compile-time for whatever
reason).  For example, if there are two very different branches of code
that should run depending on the value of parameter, and user code is
expected to want only one or the other code path, so fixing the code
path at compile-time may be advantageous.

D's operator overloading is one example of this.  It takes a
compile-time string containing the operator, which lets the implementor
choose whether to implement multiple operator overloads separately, or
grouped together in a common implementation. E.g.:

	struct MyObject {
		private int impl;

		/**
		 * Example of separate implementations for operators:
		 */
		MyObject opBinary(string op)(MyObject b)
			if (op == "*")
		{
			return ... /* multiplication algorithm here */;
		}

		/// ditto
		MyObject opBinary(string op)(MyObject b)
			if (op == "/")
		{
			return ... /* division algorithm here */;
		}

		/**
		 * Example of multiple operators sharing a common
		 * implementation.
		 */
		MyObject opBinary(string op)(MyObject b)
			if (op == "+" || op == "-")
		{
			// Use mixin to implement both operators at
			// once.  Avoids excessive boilerplate.
			return MyObject(mixin("impl" ~ op ~ "b.impl"));
		}
	}

Passing the operator as a compile-time parameter gives the flexibility
to implement different operators separately, or together with a common
implementation, or some combination of both as in the above example.


T

-- 
Real men don't take backups. They put their source on a public FTP-server and let the world mirror it. -- Linus Torvalds


More information about the Digitalmars-d-learn mailing list