Does C++/WinRT provide mapping from enum symbol to string name? - c++-winrt

I'm using C++/WinRT. The projection includes many enums. I find myself building my own table of enum values to string literals. This is not a big deal for enums with only a few defined values, but it's a pain when there are a lot of them.
What I really want is some form of compile-time or run-time reflection that converts an enum value into the string representation of the compile-time name that represents a given enum value. The code snippet below demonstrates. How can this be automated?
std::wostream& operator<< (
std::wostream& wout,
winrt::Windows::Graphics::DirectX::DirectXPixelFormat e)
{
// https://learn.microsoft.com/en-us/uwp/api/windows.graphics.directx.directxpixelformat
using winrt::Windows::Graphics::DirectX::DirectXPixelFormat;
switch (e) {
case DirectXPixelFormat::R8G8B8A8Int:
wout << L"R8G8B8A8Int";
break;
case DirectXPixelFormat::B8G8R8A8UIntNormalized:
wout << L"B8G8R8A8UIntNormalized";
break;
default:
// TODO: Many enums cases are missing.
// Find a way to compile-time-generate the string values from enum value.
wout << L"Unknown (" << std::to_wstring(static_cast<int32_t>(e)) << L")";
}
return wout;
}
I could build something that parses the winrt/*.h files to generate a header containing arrays of string literals, then #include the generated header. There probably exists sample code for doing this type of thing unrelated to C++/WinRT. But maybe C++/WinRT includes metadata in the SDK, which combined with one of the C++/WinRT command line tools, can easily do this for me? If it's there I have not found it.
I did find ApiInformation interface from winrt/Windows.Foundation.Metadata.h, as well as explanation of "Version Adaptive Code". I had hoped that OS COM interface behind ApiInformation has way to query a name for an enum value, but I was unable to find an answer there.
https://learn.microsoft.com/en-us/uwp/api/Windows.Foundation.Metadata.ApiInformation

how about this
https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/move-to-winrt-from-cx#tostring
namespace winrt
{
hstring to_hstring(StatusEnum status)
{
switch (status)
{
case StatusEnum::Success: return L"Success";
case StatusEnum::AccessDenied: return L"AccessDenied";
case StatusEnum::DisabledByPolicy: return L"DisabledByPolicy";
default: return to_hstring(static_cast<int>(status));
}
}
}

Related

How to properly log Vulkan result type strings

Logging VkResult enum values
The VkResult enum contains a lot of values. Unfortunately though, they are C enums which aliases an integer, so I cannot easily just log their names to the console. For this purpose, I am envisioning a function which does something like this:
void graphics::log_vk_result(VkResult result)
{
switch (result)
{
case VK_SUCCESS:
log_core_debug("VK_SUCCESS"); return;
case VK_NOT_READY:
log_core_debug("VK_NOT_READY"); return;
[...]
}
But some of the enum values are only supported by certain extensions, as indicated here. An example: The extension VK_EXT_debug_report introduces the following value to the enumeration: VK_ERROR_VALIDATION_FAILED_EXT. So my idea for (potentially) more portable code would be something like this:
void graphics::log_vk_result(VkResult result)
{
switch (result)
{
[...]
#if defined(VK_EXT_DEBUG_REPORT_EXTENSION_NAME)
case VK_ERROR_VALIDATION_FAILED_EXT:
log_core_debug("VK_ERROR_VALIDATION_FAILED_EXT");
#endif
}
I found this name by looking at the extension manual page. I cannot easily see whether or not VK_EXT_DEBUG_REPORT_EXTENSION_NAME is a macro or an enum - it is a const char* but stated under the section "New Enum Constants". So checking for this particular value, for this particular extension, was my default choice.
[I do realize this extension is marked as deprecated, and I'm not using it! I only use it as an example here.]
I have two questions:
Is this needed?
Is this the correct way of doing this?
Thanks a lot!
All of this is unnecessary, since Vulkan SDK already includes the desired functionality:
#include <vulkan/vk_enum_string_helper.h>
void graphics::log_vk_result( const VkResult result ){
log_core_debug( string_VkResult(result) );
}

QObject::findChildren() for QML object finding

I have an QML form with QQuickApplicationWindow. I need to get QQuickItem pointers on BaseKey elements of QtVirtualKeyboard (it's implementation is placed in separate QML file and loads with Loader of layout when program executes), but it has dynamical (runtime) type like this BaseKey_QMLTYPE_XX, where "XX" is a changeable number.
I found QObject::findChildren() function http://doc.qt.io/qt-4.8/qobject.html#findChild, but i cant find out number "XX" in typename.
How can i find QQuickItem pointer on BaseKey from C++ code?
BaseKey_QMLTYPE_XX looks like what you'd get if you printed the object (print(myObject)). I think that comes from QMetaObject::className().
If the object doesn't have an objectName set, you won't be able to find it using findChild() (unless you have access to the C++ type and there's only one object of that type).
I have a hacky test helper function that does something similar to what you're after:
QObject *TestHelper::findPopupFromTypeName(const QString &typeName) const
{
QObject *popup = nullptr;
foreach (QQuickItem *child, overlay->childItems()) {
if (QString::fromLatin1(child->metaObject()->className()) == "QQuickPopupItem") {
if (QString::fromLatin1(child->parent()->metaObject()->className()).contains(typeName)) {
popup = child->parent();
break;
}
}
}
return popup;
}
You could adapt this to iterate over the children of an object that you pass in. There are a couple more changes than that to get it to work, but the general idea is there.

Complex check-methods with boost.test

I want to test different constructors of a string class. Therefore I wrote myself a test method that checks a couple standard things:
void checkStringStandards(String& s, size_t length, const char* text){
BOOST_CHECK_EQUAL(s.length(), length);
...
}
Then I added a test method
BOOST_AUTO_TEST_CASE(String_construct){
String s1;
checkStringStandards(s1, 0, "");
String s2("normal char");
checkStringStandards(s2, 11, "normal char");
}
The problem is, that when it fails, I only get the line- and file information from within checkStringStandards ! I can't know by the output whether the first or the second call caused this.
What's the common fix for that?
Cheers!
The solution to this problem is to write a custom predicate that performs the checks and use BOOST_REQUIRE(custom_predicate(args)) in the different test cases. A custom predicate can take any arguments you want and returns boost::test_tools::predicate_result, a type that is compatible with the assertion macros in Boost.Test into which you can build up a detailed diagnostic message during failure.
To use your example:
using namespace boost::test_tools;
predicate_result checkStringStandards(String& s, size_t length, const char* text) {
predicate_result result{true};
if (s.length() != length) {
result = false;
result.message() << "\nString " << s
<< " differs in length; expected: "
<< length << ", actual: " << s.length();
}
...
return result;
}
BOOST_AUTO_TEST_CASE(String_construct){
String s1;
BOOST_REQUIRE(checkStringStandards(s1, 0, ""));
String s2("normal char");
BOOST_REQUIRE(checkStringStandards(s2, 11, "normal char"));
}
The curious \n at the beginning of the message is so that when the diagnostic is printed, the text with "String ... differs in length" will be emitted on it's own line. If the predicate fails, it bubbles its failure up to BOOST_REQUIRE which will trigger the test failure and report the failure at the line invoking BOOST_REQUIRE instead of inside your custom predicate.
There is another yuckier alternative that also achieves the same result by making your custom assertions as gigantic megamacros, but I find that so horrid I'm not even going to show an example of how to do it :).
there is no common fix for that. these BOOST_CHECK_... macros exist by intention to avoid function calls where the line number gets lost (unless explicitely passed as param).
you can get round this problem by looping through the parameter set inside your test case.

How to avoid if else or switch case whe dealing with enums?

I have a member variable that tells units for a value I have measured like centimeters,kilometers,seconds,hours etc.
Now these are enums,
When I display a corresponding string, I have created a method that returns corresponding string for these enums.
Unlike Java, enums here cant have other properties associated with them.
So I have to explicitly do a if-else-if chain or a switch case to return the correct string.
I am new to Objective C. any good practice that I should be following in such scenarios ?
afaik Objective-C enums are just old-school C enums... so maybe you can use an integer value for them?
I guess if your enum values started at 0 and increased you could use some sort of array access:
const char *distanceUnitToString2(enum DistanceUnit unit)
{
const char *values[] = {
"cm",
"m",
"km"
};
// do some sanity checking here
// ...
return values[unit];
}
But this feels a little flaky to me. What if you have negative values, or you are using bitmask-style enum values like 1 << 8? You are going to end up using a very large array.
You also could use a switch and improve it a little with a macro. Something like this:
const char *distanceUnitToString(enum DistanceUnit unit)
{
#define CASE(UNIT, STRING) case (UNIT): return (STRING)
switch (unit) {
CASE(kCentimeters, "cm");
CASE(kMeters, "m");
CASE(kKiloMeters, "km");
default:
// should not get here
assert(0);
break;
}
#undef CASE
}
But you don't really save that much vs. not using the macro.
Martin James's comment is the right answer. And use a definition of the enum like:
enum units { cm = 0, m, km };
that way you can be sure that your enum translates to the correct index values.

Casting a basic CFTypeRef to a more specific CoreFoundation type

Is there a simple way to convert a CTypeRef to a specific CoreFoundation type? I'm not looking to cast inline as (CFStringRef)myObjectRef but would like to create a helper method to do this for me for all CoreFoundation types.
I know it's possible to use something like CFGetTypeID(myObjectRef) == CFStringGetTypeID() to find out whether a CTypeRef is a CFString. However creating a single method to do this could become very verbose and have a lot of if statements.
Is building out a method with a bunch of if statements against CFGetTypeID() the only way? Or is there a simpler way to do this?
UPDATE: with example
I'd like to make a helper function to work with some legacy code I can't change. Currently it produces one of CFDictionaryRef, CFStringRef or CFURLRef as a return value provided as a CTypeRef. I'm currently working around this by running CFGetTypeID() on the returned value but this isn't ideal. Rather than having C-style casts all over the place, I'd rather have a CastToCF() helper which handles this for me. This would help make testing easier in the future as well.
P.S. I'm not worried about mutable types.
there's no obvious point in doing this. a c style cast is not like other languages - it is a typecast which the address on the left will be identical to the address on the right. cftypes will not throw or return null if you do a bad cast (unlike other languages). iow, it's merely a decoration for you to specify a type, and a c compiler will assume your cast is valid.
or perhaps you can provide a better example of how you would use this, if that did not help.
Update
ok. since you tagged it objc++, i'd just create a helper class which had plenty of diagnostics and did all the noisy conversions (minimal illustration):
class t_helper {
public:
t_helper(CFTypeRef cf) : d_cf(cf), d_type(CFGetTypeID(cf)) { assert(this->d_cf); }
~t_helper() {}
/* type info */
bool isString() const { return CFStringGetTypeID() == this->type(); }
CFStringRef string() { assert(this->isString()); return this->cf_cast<CFStringRef>(); }
bool isDictionary() const { return CFDictionaryGetTypeID() == this->type(); }
CFDictionaryRef dictionary() { assert(this->isDictionary()); return this->cf_cast<CFDictionaryRef>(); }
...
/* and a trivial example of an operation */
void appendMutableCopyToArray(CFMutableArrayRef array) {
if (this->isString()) {
CFMutableStringRef cp(CFStringCreateMutableCopy(0,0,this->string()));
CFArrayAppendValue(array, cp);
CFRelease(cp);
}
...
}
...
private:
template < typename T > T cf_cast() { return reinterpret_cast<T>(this->d_cf); }
const CFTypeID type() const { return this->d_type; }
private:
CFTypeRef d_cf;
const CFTypeID d_type;
};
that's about as accurate as i can get get without a really specific example of the program you are dealing with.