由于非类型模板参数而具有零大小数组的类模板:如何防止警告

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

本文关键字:数组 警告 小数 何防止 参数 类型 于非      更新时间:2023-10-16

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

#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]

这绝对没问题,但我想知道如何防止此消息?

您可以将A结构专门用于L == 0以下情况

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