gpt4 book ai didi

c++ - 将可变数量的数组引用传递给具有可变参数模板的函数

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

我知道如何编写接受可变数量参数的可变参数模板函数:

template<int I, typename... Rest>
void f() {
// whatever
}

而且我知道如何编写接受数组引用的模板函数:

template<typename T, unsigned int Length>
void f(T(&arr)[Length]) {
// whatever
}

但我想不出如何将两者结合起来,以便函数接受可变数量的数组引用。

我的第一次尝试是

template<typename T, unsigned int Length>
unsigned int arrlen(T(&)[Length]) {
return Length;
}

template<typename T, unsigned int Length>
int f(T(&arr)[Length]) {
return Length;
}

template<typename T, unsigned int Length, typename... Rest>
int f(T(&arr)[Length], Rest... rest) {
return Length + f(rest...);
}

int main() {
int a[] = {1 , 2, 3}, b[] = {1, 2, 3, 4, 5}, c[] = {1};

cout << f(a, b, c);
}

但是编译器告诉我

a.cpp: In function 'int f(T (&)[Length], Rest ...) [with T = int, unsigned int Length = 3u, Rest = {int*, int*}]'

a.cpp:23:22: instantiated from here

a.cpp:17:27: error: no matching function for call to 'f(int*&, int*&)'

a.cpp:17:27: note: candidates are:

a.cpp:11:22: note: template int f(T(&)[Length])

a.cpp:16:5: note: template int f(T(&)[Length], Rest ...)

所以我在想,您可以编写一个对象来存储构造数组的长度,然后将可变数量的数组(从传递的数组隐式构造)传递给函数。这是我的尝试:

template<typename T, unsigned int Length>
struct Array {
Array(T(&arr)[Length]) : arr(arr), len(Length) { }

T(&arr)[Length];
const unsigned int len;
};

int f() {
return 0;
}

template<typename T, unsigned int Length, typename... Args>
int f(const Array<T, Length>& a1, Args... rest) {
return a1.len + f(rest...);
}

int main() {
int a[] = { 1, 2, 3 }, b[] = { 1, 2, 3, 4, 5 }, c[] = { 1 };

cout << f(a, b, c);
}

但是当我尝试使用 GCC 4.6.1 编译它时出现错误

a.cpp: In function 'int main()':

a.cpp:27:22: error: no matching function for call to 'f(int [3], int [5], int [1])'

a.cpp:27:22: note: candidates are:

a.cpp:16:47: note: template int f(const Array&, Args ...)

a.cpp:20:5: note: int f()

a.cpp:20:5: note: candidate expects 0 arguments, 3 provided

但是,除了修复第二个代码(这更像是一种不知道如何做我真正想做的事情的解决方法)之外,这个问题的实际意义和我真正想学习的是如何做如果可能的话,这不会像第一个代码那样使用代理对象。那么如何做到这一点呢?我发布的其中一个尝试是否只是一个简单的语法错误?

最佳答案

如果你只是想求和一些数组的长度,你可以直接这样做:

template<typename T, unsigned int Length>
int f(const T (&)[Length]) {
return Length;
}

template<typename T, unsigned int Length, typename... Args>
int f(const T (&)[Length], Args&... rest) {
return Length + f(rest...);
}

int main() {
int a[] = { 1, 2, 3 }, b[] = { 1, 2, 3, 4, 5 }, c[] = { 1 };

std::cout << f(a, b, c);
}

关于c++ - 将可变数量的数组引用传递给具有可变参数模板的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9232445/

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