Asking types about their traits (D 1.0)

Burton Radons burton-radons at shaw.ca
Sun Feb 10 16:01:12 PST 2008


I'm writing some templated code that I want to automatically behave properly when applied to any other type which behaves according to an interface. There are two sides to this. The first is when I want to test for it behaving like an integer. In this case, if I already have an algorithm written for an integer, then it should work for it automatically. In the other case, I want to be able to ask it whether it implements a method, such as "pow". Then I'd call that method instead of using my own code, which may be suboptimal.

Both of these are implementable by having an alias or typedef in the type, such as with:

	/// A dummy type that is used to indicate the presence of a trait.
	struct Trait
	{
	}
	
	struct Bignum 
	{
		/// Traits supported by Bignum.
		alias Trait IsInt, HasPow;

		// We're an integer type so our pow function works just fine, but we can implement it faster and control our temporaries.
		Bignum pow (Bignum value) { ... }
	}
	
	/// Evaluates to true if the type is a builtin integral type (byte, ubyte, short, ushort, int, uint, long, ulong) or if it has the IsInt trait.
	template is_int (T)
	{
		const bool is_int = is_type! (T, byte, ubyte, short, ushort, int, uint, long, ulong) || is (T.IsInt == Trait);
	}

	/// Evaluate to true if T is any of the given types.
	template is_type (T, Y...)
	{
		static if (Y.length > 1)
			const bool is_type = is (T == Y [0]) || is_type! (T, Y [1 .. $]);
		else static if (Y.length == 1)
			const bool is_type = is (T == Y [0]);
		else
			const bool is_type = false;
	}

	is_int! (int) == true;
	is_int! (float) == false;
	is_int! (Bignum) == true;

But I'd like it if the presence of a method didn't require a superfluous alias, but could be detected automatically with something like "is (T.pow : T delegate (T))". Any ideas?

Maybe I shouldn't be fighting this - the presence of a method even with the correct signature doesn't necessarily imply that it supports the functionality we're requesting. On the other hand, the likelihood of incorrect code being generated seems extremely minute versus the expense of the alias. What do you think?


More information about the Digitalmars-d-learn mailing list