简体   繁体   English

std :: decay一个零长度数组

[英]std::decay an zero length array

I am dealing with some legacy C structures - where we have zero length array. 我正在处理一些遗留的C结构 - 我们有零长度数组。 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. 我正在写一个宏,我想使用std :: decay将数组衰减到指针类型。

But if I have a zero length array - 但如果我有一个零长度数组 -

struct data {
   key[0]; <<
};

std::decay<decltype(data::key)> doesnt decay to pointer type. std::decay<decltype(data::key)>不会衰减为指针类型。 I am using this as a function return type, and it complains - 我使用它作为函数返回类型,它抱怨 -

GCC Error: GCC错误:

error: 'function' declared as function returning an array 错误:'function'声明为返回数组的函数

It works fine if its an array of length >= 1 如果它的长度> = 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, "");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM