繁体   English   中英

由于非类型模板参数而导致数组大小为零的类模板:如何预防警告?

[英]Class-template with zero-size array due to non-type template parameter: how to prevent warning?

我使用类似以下最小示例的代码:

#include <stdint.h>

constexpr uint8_t size = 0; // sort of global config option

template<typename T = char, uint8_t L = size>
struct A {
    T f() {
        if constexpr(L > 0) {
            return data[0];
        }  
        return T{0};
    }
    int x = 0;
    T data[L];
};

int main() {
    A x; 
    x.f();
}

现在,我将编译器(g ++)设置更改为-pedantic,并收到以下警告:

ISO C++ forbids zero-size array [-Wpedantic]

绝对可以,但是我想知道如何防止此消息?

您可以针对L == 0的情况专门化A结构:

template <typename T>
struct A<T, 0>
{
  T f() { return {0}; }
};

暂无
暂无

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

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