gpt4 book ai didi

c++ - 数组作为非类型模板参数

转载 作者:太空狗 更新时间:2023-10-29 21:37:27 25 4
gpt4 key购买 nike

我注意到了

template <size_t n, char[n]> class x
{
};

很高兴地被我的 C++ 编译器接受了。然而,当我天真地尝试类似的东西时

x <4, "hey"> something;

我得到了一个很好的

Non type template argument does not refer to any declaration

所以我想知道:我将如何使用该模板实际创建一个类?

最佳答案

#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;

潜在的缓冲区溢出问题。

关于c++ - 数组作为非类型模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37690788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com