简体   繁体   English

使用模板时初始化数组

[英]Initializing arrays when using templates

Let's say I have the class Foo . 假设我上了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};
        }
};

My understanding of the way templates work is that A and B are essentially compile time constants, so it should still work the same. 我对模板的工作方式的理解是, AB本质上是编译时间常数,因此它应该仍然相同。

The error message I get when compiling with g++ (4.5 in the link, same error with 4.6.3) is: 使用g ++编译 (链接中为4.5,与4.6.3相同的错误),我收到的错误消息是:

error: ISO C++ forbids initialization in array new [-fpermissive] 错误:ISO C ++禁止在数组new [-fpermissive]中初始化

With 4.7 a similar error occurs, though slightly different: 对于4.7,会发生类似的错误,尽管略有不同:

error: parenthesized initializer in array new [-fpermissive] 错误:新数组[-fpermissive]中带括号的初始化程序

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) (感谢菲利普)

Looks like this is a GCC bug. 看起来这是一个GCC错误。 Clang accepts it, and the standard allows it: Clang接受它,并且标准允许它:

new-initializer: 新初始化:

( expression-list opt ) ( expression-list opt )
braced-init-list 支撑-初始化列表

And the rules for this initialization are not special: 而且此初始化的规则并不特殊:

A new-expression that creates an object of type T initializes that object as follows: 创建一个T类型对象的new表达式按如下方式初始化该对象:

— If the new-initializer is omitted, the object is default-initialized (8.5); —如果省略了new-initializer ,则该对象为默认初始化 (8.5);否则为false。 if no initialization is performed, the object has indeterminate value. 如果未执行初始化,则该对象具有不确定的值。

— Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization . —否则,将根据8.5的初始化规则对new-initializer进行解释以进行直接初始化

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

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