假设我有 Foo
类。以下工作正常:
class Foo
{
public:
const int* bar;
Foo()
{
bar = new int[2] {1, 2};
}
};
但是,我尝试稍微更改一下以使用模板:
template<int A, int B>
class Foo
{
public:
const int* bar;
Foo()
{
bar = new int[2] {A, B};
}
};
我对模板工作方式的理解是,A
和 B
本质上是编译时常量,因此它应该仍然可以正常工作。
编译时收到的错误消息with g++ (链接中的4.5,与4.6.3相同的错误)是:
error: ISO C++ forbids initialization in array new [-fpermissive]
With 4.7出现类似的错误,但略有不同:
error: parenthesized initializer in array new [-fpermissive]
该问题也出现在模板函数中,而不仅仅是在大括号内使用模板参数进行初始化时,code and output 。 (感谢菲利普)
最佳答案
看起来这是一个 GCC 错误。 Clang 接受它,并且标准允许它:
new-initializer:
block 引用>
(
expression-listopt)
braced-init-list而且这个初始化的规则并不特殊:
A new-expression that creates an object of type
T
initializes that object as follows:— If the new-initializer is omitted, the object is default-initialized (8.5); 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.
关于c++ - 使用模板时初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9894406/