0

This works fine

const void* getObjHandle() {
 return (const void*)hdl;
}

But the below gives ignored-qualifiers warning.

error: type qualifiers ignored on function return type [-Werror=ignored-qualifiers]

typedef void* objHandle;
const objHandle getObjHandle() {
 return (const objHandle)hdl;
}

The below one gives an invalid static_cast error along with the ignored-qualifiers warning

error: invalid static_cast from type ‘const Object*’ to type ‘const objHandle {aka void* const}’

typedef void* objHandle;
const objHandle getObjHandle() {
 return static_cast<const objHandle>(hdl);
}

The below one works again

typedef void* objHandle;
const void* getObjHandle() {
 return static_cast<const void*>(hdl);
}

hdl is a const pointer to an object I am getting from another helper inside getObjHandle(). Why are these warnings/errors coming? How can I get rid of them without getting rid of the typedefs.

Saynb
  • 55
  • 8

1 Answers1

2

These two are not the same due to how C++ qualifiers are syntactically defined:

using one = const T*;

using pointer = T*
using const_pointer = const pointer;

The latter const is applied to the outside of type pointer, which is the pointer type, not the type pointed to.

Note you can always put const after the type you need it applied to, which is actually the most robust and confusion-free yet awkward in the common "const ref" situation:

using pointer_to_const = T const *;

using pointer = T*;
using const_pointer = pointer const;

Here, you can immediately see through substitution that const_pointer ends up as T* const which is not the same as pointer_to_const.

There is no way to "inject" a const inside an previously defined type alias, you can only slap it on the outside (i.e. right side) of the aliased type.

rubenvb
  • 74,642
  • 33
  • 187
  • 332
  • That cleared it up. Thanks! I didn't realize it was a const placement issue. Is there a better way to "typedef" void pointers ? – Saynb May 11 '18 at 09:41
  • 1
    @Saynb: Yes: don't. And while you're at it, don't use `void*`. We have templates for a reason ;). – rubenvb May 11 '18 at 09:42