使用指针作为模板非类型参数

tow*_*ism 4 c++ arrays templates pointers callback

我想使用数组指针(带数组运算)作为非类型参数.我知道这个参数应该在编译时知道,但对于固定大小的全局数组不是这样吗?

此示例可以打印前两行,但不能打印第三行.这有什么解决方法吗?

编辑:我在寻找的不仅是一个答案aa+1,但所有aa+is其中i小于大小aa

#include <iostream>

void print (int n) {
    printf("the value is: %d\n", n);
}

template <int *n>
void myWrapper() {
    print(*n);
}

void myCall(void (*CALLBACK)(void)) {
    CALLBACK();
}

int a = 1; int aa[4] = {2,3,4,5}; 

int main()
{
    myCall(myWrapper<&a>); // prints 1
    myCall(myWrapper<aa>); // prints 2
    /* the following line gives error: no matches converting function 'myWrapper' to type 'void (*)()' 
       note: candidate is: template<int* n> void myWrapper() 
    */
    myCall(myWrapper<aa+1>); 
}
Run Code Online (Sandbox Code Playgroud)

eca*_*mur 6

这被[temp.arg.nontype]的注释所排除:

3 - [ 注意:数组元素的地址和非静态类成员的名称或地址是不可接受的 模板参数.[...]

解决方法可能是将数组索引作为另一个模板参数提供:

template <int *n, unsigned N = 0>
void myWrapper() {
    print(n[N]);
}

// ...
myCall(myWrapper<aa, 1>); 
Run Code Online (Sandbox Code Playgroud)