Std :: decay of zero length array
I am dealing with some legacy C structs where we have a zero length array. I think this is not true, but we have to live with him. I was writing a macro and I want to decompose an array to a pointer type using std :: decay.
But if I have a zero length array -
struct data {
key[0]; <<
};
std::decay<decltype(data::key)>
does not decay to pointer type. I am using this as the return type of a function and it complains -
GCC error:
error: 'function declared as a function returning an array
It works fine if its array is> = 1 long
+3
source to share
1 answer
We could let the compiler type checking, instead of replacing the template, do the decay for us:
#include <type_traits>
template <typename T>
T* as_ptr(T* x) { return x; }
template <typename T>
using DecayToPointer = decltype(as_ptr(std::declval<T>()));
int main() {
static_assert(std::is_same<DecayToPointer<int[0]>, int*>::value, "");
static_assert(std::is_same<DecayToPointer<int[1]>, int*>::value, "");
static_assert(std::is_same<DecayToPointer<int[]>, int*>::value, "");
}
0
source to share