繁体   English   中英

零大小的数组不适用于模板

[英]Zero-sized arrays don't work with templates

使用GCC时,似乎模板参数替换始终失败,并且数组大小为零。 我希望static_assert失败并在test1打印消息,就像在test2
您也可以删除static_assert ,该模板不适用于零大小的数组。

由于零大小数组是扩展,因此在C ++标准中肯定没有关于特殊处理的规则,所以我的问题是:
我是否想念某些东西,这是一个错误还是GCC作者的意图?

#include <iostream>

template <size_t len>
void test1(const char(&arr)[len])
{
    static_assert(len > 0, "why am I never printed?");
}

template <size_t len>
void test2(const char(&arr)[len])
{
    static_assert(len > 10, "I will be printed");
}

int main()
{
    char arr5[5];
    test2(arr5);

    char arr0[0];
    test1(arr0);
}

错误输出:

main.cpp: In function ‘int main()’:
main.cpp:21:15: error: no matching function for call to ‘test1(char [0])’
     test1(arr0);
               ^
main.cpp:21:15: note: candidate is:
main.cpp:4:6: note: template<unsigned int len> void test1(const char (&)[len])
 void test1(const char(&arr)[len])
      ^
main.cpp:4:6: note:   template argument deduction/substitution failed:
main.cpp: In instantiation of ‘void test2(const char (&)[len]) [with unsigned int len = 5u]’:
main.cpp:18:15:   required from here
main.cpp:12:5: error: static assertion failed: I will be printed
     static_assert(len > 10, "I will be printed");
     ^

我的编译器版本是:

g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4

更新:我今天用Visual C ++ 2015测试了它,它显示了相同的行为。 VC ++仅支持零大小的数组,只要它们是类/结构的最后一个成员,但是如果代码进行了相应的更改,则它与g ++完全相同:

函数模板永远不会使用零大小的数组进行编译。 为什么?

#include <iostream>

struct s_arr
{
    char arr0[0];
};

template <size_t len>
void test(const char(&arr)[len])
{
}

int main()
{
    s_arr s;
    test1(s.arr0);
}

我是否想念某些东西,这是一个错误还是GCC作者的意图?

在模板中接受零大小的数组将导致一致性问题或无法维护的语言。

给定

template <int N> void f(char (*)[N], int);
template <int N> void f(void *, void *);

调用f<1>(0, 0) 必须使用第一个重载,因为它与第二个参数更好地匹配。

调用f<0>(0, 0) 必须使用第二个重载,因为SFINAE会由于数组大小为零而丢弃第一个重载。

零大小的数组可以作为扩展名使用,只要它们不改变任何标准C ++程序的语义即可。 在模板参数替换期间允许零大小的数组将改变标准C ++程序的语义,除非在不允许零大小的数组的地方实现了完整的例外列表。

暂无
暂无

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

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