模板指针参数包

GSi*_*GSi 6 c++ templates language-lawyer variadic-templates

为什么带有模板参数包指针的模板函数无法使用相同指针的偏移量进行实例化?

我的意思是:给出这个简短的代码为什么我必须注释掉最后两行?

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
}
Run Code Online (Sandbox Code Playgroud)

并不n+1代表相同的地址&m?或者链接有什么不同?还有什么?

Ola*_*che 3

请参阅cppreference.com - 模板非类型参数

  • 对于指向对象的指针,模板参数必须指定具有静态存储持续时间和链接(内部或外部)的对象的地址,或者指定计算结果为适当的空指针或 std::nullptr_t 值的常量表达式。

...

唯一的例外是引用和指针类型的非类型模板参数不能引用/成为

  • 子对象(包括非静态类成员、基子对象或数组元素);
  • 临时对象(包括在引用初始化期间创建的临时对象);

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