开发者问题收集

数组作为非类型模板参数

2016-06-07
1655

我注意到

991258032

我的C ++编译器很高兴接受。但是,当我天真地尝试

758559725

我得到一个不错的

469285444

所以我想知道:实际上是用该模板上课的?

2个回答
#include <iostream>

template <size_t n, char s[n]>
class X {
public:
  X() {
    std::cout << s;
    std::cout << std::endl;
  }
};

char hey[] = "hey";

int main() {
  X<4, hey> x;
}

但是 X<4, "hey"> x; 无法编译,因为对于非类型模板参数,存在某些限制:

For pointers to objects, the template arguments have to designate the address of an object with static storage duration and a linkage (either internal or external), or a constant expression that evaluates to the appropriate null pointer or std::nullptr_t value.

这引发了另一个问题,我在 cppreference.com 上发现了以下内容:

Array and function types may be written in a template declaration, but they are automatically replaced by pointer to object and pointer to function as appropriate.

因此 s 实际上是一个指针,因此以下内容可以编译:

X<5, hey> something;

潜在的缓冲区溢出问题。

xiaofeng.li
2016-06-07
template <size_t n, char[n]> class x
{
};

char foobar[]="hey";

x<4, foobar> y;

使用 gcc 5.3.1 进行编译

Sam Varshavchik
2016-06-07