Asking types about their traits (D 1.0)

downs default_357-line at yahoo.de
Wed Feb 13 04:11:19 PST 2008


Burton Radons wrote:
> 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.
> 

It sounds like you want something like Duck Typing :)

Example.

template Init(T) { T Init; }

template behavesLikeInt(T) { // tests, basically, if T * int -> :int

	const bool behavesLikeInt = is(typeof(Init!(T) * 2) : int);
}

template hasPowWithInt(T) {
	const bool hasPowWithInt = is(typeof(Init!(T).pow(2)));
}

Does that help?

 --downs


More information about the Digitalmars-d-learn mailing list