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

wim*_*aan 0 c++ templates

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

#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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

piw*_*iwi 6

您可以A根据以下情况对结构进行专门化L == 0:

template <typename T>
struct A<T, 0>
{
  T f() { return {0}; }
};
Run Code Online (Sandbox Code Playgroud)