使用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 ++程序的语义,除非在不允许零大小的数组的地方实现了完整的例外列表。
关于c++ - 零大小的数组不适用于模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33510098/