Is Key Type?

Gary Willoughby via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 2 11:21:58 PDT 2015


On Sunday, 2 August 2015 at 17:55:16 UTC, Xinok wrote:
> is there a trait in D or Phobos which will tell you if a type 
> can be used as a key for an associative array? For example, 
> where T is some type:
>
>     static assert(isKeyType!T)
>     int[T] hashTable = ...

import std.stdio;

enum isKeyType(T) = __traits(compiles, int[T]);

class Foo {}
struct Bar {}

void main(string[] args)
{
	// Success
	assert(isKeyType!(int));
	assert(isKeyType!(string));
	assert(isKeyType!(Foo));
	assert(isKeyType!(Bar));

	// Fail
	assert(isKeyType!(void));
	assert(isKeyType!(delegate(){}));
	assert(isKeyType!(function(){}));
}


More information about the Digitalmars-d-learn mailing list