What are some ways to get more strict type-checking?

Devin lee.hastings at outlook.com
Tue May 7 14:50:04 UTC 2019


On Tuesday, 7 May 2019 at 13:46:55 UTC, Devin wrote:
> [snip]

I'm wrapping around OpenGL, which uses a int and uint for 
numerous types, so I decided to make a mixin template for making 
a sort of strict alias type.  Importantly, they aren't assignable 
to each other, unlike Typedef.

Here's the template I'm trying:

mixin template StrictAlias(T)
{
	private T _handle;

	@disable this(U)(U u);

	this(U : U)(U data) if( is(U == T) )
	{
		_handle = data;
	}

	@property T handle()
	{
		return _handle;
	}

	alias handle this;
}

And here's how I'm using it:

struct MaterialId
{
	mixin StrictAlias!GLuint;
}
struct UniformId
{
	mixin StrictAlias!GLint;
}
struct AttribId
{
	mixin StrictAlias!GLint;
}

So now I can easily call OpenGL functions using values of these 
types, but I can't accidentally assign one to the other, and I 
can only construct them with exactly the type they alias.  Thanks 
for the tips!



More information about the Digitalmars-d-learn mailing list