Enum that can be 0 or null

tsbockman via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 20 23:36:53 PDT 2016


On Saturday, 21 May 2016 at 01:09:42 UTC, Alex Parrill wrote:
> On Friday, 20 May 2016 at 22:10:51 UTC, tsbockman wrote:
>> If that's not a satisfactory answer, please show some specific 
>> examples of code that you don't know how to make work without 
>> VK_NULL_HANDLE so that I can propose a workaround.
>
> Because, as I mentioned in the OP, for VK_NULL_HANDLE to work 
> like it does in C on 32-bit systems, it needs to be compatible 
> with both pointer types (VkDevice, VkInstance, etc) and 64-bit 
> integer types (VkFence, VkSemaphore, many others).

That is not code. As I said, there are many possible workarounds, 
but it is hard to say which is best for you without actually 
seeing your code.

As an example, if VK_NULL_HANDLE only ever needs to be assigned 
to opaque types on the D side (that is, types that serve only as 
an ID or address for communicating with the C side), you could do 
this:

private struct VkNullHandle { }
enum VK_NULL_HANDLE = VkNullHandle.init;

mixin template VkHandle(bool dispatchable) {
	static if (dispatchable || (size_t.sizeof == 8))
		void* bits = null;
	else
		ulong bits = 0;
	
	this(typeof(this) that) {
		this.bits = that.bits; }
	this(VkNullHandle that) {
		this.bits = typeof(this.bits).init; }

	ref typeof(this) opAssign(typeof(this) that) {
		this.bits = that.bits;
		return this;
	}
	ref typeof(this) opAssign(VkNullHandle that) {
		this.bits = typeof(this.bits).init;
		return this;
	}
}

struct VkDevice { mixin VkHandle!true; }
struct VkInstance { mixin VkHandle!true; }

struct VkFence { mixin VkHandle!false; }
struct VkSemaphore { mixin VkHandle!false; }


void main() {
	VkInstance a = VK_NULL_HANDLE;
	VkFence b = VK_NULL_HANDLE;
}

(DPaste: https://dpaste.dzfl.pl/8f4ce39a907f )

The above is typesafe, and can easily be made compatible with a 
typical C API, since C does no parameter-related name mangling.


More information about the Digitalmars-d-learn mailing list