在使用模板时初始化数组 [英] Initializing arrays when using templates
问题描述
假设我有 Foo
类。以下工作正常:
Let's say I have the class Foo
. The following works fine:
class Foo
{
public:
const int* bar;
Foo()
{
bar = new int[2] {1, 2};
}
};
但是,我试图稍微改变一下使用模板:
However, I tried to change this very slightly to use a template:
template<int A, int B>
class Foo
{
public:
const int* bar;
Foo()
{
bar = new int[2] {A, B};
}
};
我对模板工作方式的理解是 A
和 B
本质上是编译时常数,所以它应该仍然工作相同。
My understanding of the way templates work is that A
and B
are essentially compile time constants, so it should still work the same.
错误消息I编译 g ++ (链接中为4.5,与4.6.3出现同一错误)时得到的是:
The error message I get when compiling with g++ (4.5 in the link, same error with 4.6.3) is:
错误:ISO C ++禁止在数组中初始化new [-fpermissive]
error: ISO C++ forbids initialization in array new [-fpermissive]
使用4.7 会出现类似错误,但略有不同:
With 4.7 a similar error occurs, though slightly different:
错误:数组中的括号初始化器new [-fpermissive]
error: parenthesized initializer in array new [-fpermissive]
模板函数,而不仅仅是在大括号中使用模板参数进行初始化时,代码和输出。 (感谢Philipp)
The problem also occurs in template functions, and not just when template parameters are used within the braces for initialization, code and output. (thanks Philipp)
推荐答案
看起来这是一个GCC错误。 Clang接受它,标准允许它:
Looks like this is a GCC bug. Clang accepts it, and the standard allows it:
new-initializer: b
(
expression-list opt)
braced-init-list
(
expression-listopt)
braced-init-list
此初始化的规则不是特殊的:
And the rules for this initialization are not special:
创建
T
类型的对象初始化
对象,如下所示:
A new-expression that creates an object of type
T
initializes that object as follows:
如果省略 new-initializer ,则对象为
默认初始化(8.5);如果不执行初始化,
对象具有不确定的值。
— If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value.
- 否则,新的初始化器是
根据8.5的初始化规则对直接初始化进行解释。
— Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.
这篇关于在使用模板时初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!