gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:50 25 4
gpt4 key购买 nike

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

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

编辑:我不仅在寻找aa+1的答案,而且还在寻找所有aa+i的答案,其中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>);
}

最佳答案

[temp.arg.nontype] 的注释排除了这一点:

3 - [ Note: Addresses of array elements and names or addresses of non-static class members are not acceptable template-arguments. [...]

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

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

// ...
myCall(myWrapper<aa, 1>);

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

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