I am dealing with some legacy C structures - where we have zero length array. I think it is not valid, but we have to live with it. I was writing a macro, and I want to decay array to pointer type using std::decay.
But if I have a zero length array -
struct data {
key[0]; <<
};
std::decay<decltype(data::key)>
doesnt decay to pointer type. I am using this as a function return type, and it complains -
GCC Error:
error: 'function' declared as function returning an array
It works fine if its an array of length >= 1
We could let the compiler's type checker, instead of template substitution, to 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, "");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.