gpt4 book ai didi

c++ - 模板指针参数包

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:33:20 24 4
gpt4 key购买 nike

为什么不能使用相同指针的偏移量来实例化具有指针模板参数包的模板函数?

我的意思是:鉴于这段简短的代码,为什么我必须注释掉最后两行?

template <int * ... pt> void f() {}

int n[] = {1, 2, 3};
int m = n[1];

int main()
{
f<n>(); // this is accepted
f<n, &m>(); // this is accepted too
//f<n, n+1>(); // this is not.
//f<n, &n[1]>(); // this isn't accepted neither
}

n+1 不代表与 &m 相同的地址吗?还是联动有区别?或者还有什么?

最佳答案

参见 cppreference.com - Template non-type arguments

  • 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.

...

The only exceptions are that non-type template parameters of reference and pointer type cannot refer to/be the address of

  • a subobject (including non-static class member, base subobject, or array element);
  • a temporary object (including one created during reference initialization);

所以数组元素的地址是不允许的。

关于c++ - 模板指针参数包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48753064/

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