Does C++/WinRT offer a helper function to construct a GUID from a string literal?

3

Unlike C++/CX, there doesn't appear to be a wrapper type for GUIDs in C++/WinRT. It just uses the plain C GUID struct as-is. So the only way to construct an initialized GUID is by using aggregate initialization syntax, e.g.

GUID const guid{ 0x00000000, 0x0000, 0x0000,{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } };

While that works (and the Create GUID tool in Visual Studio can even be set to generate the initializer code for you) it's just tedious, far from readable, and always has me scratching my head whether I introduced any endian-ness issues.

I'd much rather like to write (using a hypothetical make_guid function)

auto const guid{ make_guid("00000000-0000-0000-0000-000000000000") };

I know that C++/WinRT does a lot of constexpr magic to calculate GUIDs from fully-qualified type names, so presumably it is possible to implement a zero-overhead compile time make_guid function. Browsing the documentation and winrt/base.h, I didn't spot anything that's immediately applicable.

Does C++/WinRT provide a helper function to construct a GUID from a string literal at compile time? If not, can we/I have one?

c++-winrt
asked on Stack Overflow Jul 13, 2018 by IInspectable • edited Jul 13, 2018 by IInspectable

2 Answers

4

No, C++/WinRT does not currently provide such a helper. When the constexpr GUID code was originally written, the C++ compiler's support for constexpr was rather brittle and slow. I thus avoided any unnecessary computation. The constexpr support has however improved quite a bit. Anyway, a constexpr make_guid function is doable with a sufficiently advanced compiler. Here is an example:

https://gist.github.com/kennykerr/6c948882de395c25b3218ad8d4daf362

answered on Stack Overflow Jul 16, 2018 by Kenny Kerr
0

The answer from Kenny is very helpful. I am just adding a bit update on GUID in Windows 10 SDK.

GUID has been projected to "winrt::guid" since Windows 10, version 1809. And it is now a fundemental type in C++/WinRT. Here is the release note on Docs.

Beside, there is a helper to construct a GUID from empty. Please refer to the link below: https://docs.microsoft.com/en-us/uwp/api/windows.foundation.guidhelper.createnewguid?view=winrt-19041

answered on Stack Overflow Apr 8, 2021 by Jeff

User contributions licensed under CC BY-SA 3.0