gpt4 book ai didi

c++ - 带递归的可变参数函数

转载 作者:行者123 更新时间:2023-11-28 04:33:16 25 4
gpt4 key购买 nike

我试图编写一个带有可变参数的递归函数来复制我的数据。但是这个函数只复制最后一个参数。我做错了什么?

这是输出:

13 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

12 0 0 0 0 0 0 0 0 0 0 0

最好的问候。

#include <iostream>
#include <cstdint>
#include <cstring>
using namespace std;

void copy_data(unsigned char* ar, unsigned& offset, int data) {
std::memcpy(ar + offset, (void*)&data, sizeof(data));
offset += sizeof(data);
}

template<class... Args>
void copy_data(unsigned char* ar, unsigned& offset, int data, Args... args) {
if ((sizeof...(Args)) == 0) {
copy_data(ar, offset, data);
}
copy_data(ar, offset, args...);
}

void printf_data(const unsigned char* ar, int s) {
for (int i = 0; i < s; ++i) {
std::cout << (int)ar[i] << " ";
}
std::cout<<"\n";
}

int main() {
unsigned char *arr0 = new unsigned char[16];
unsigned char *arr1 = new unsigned char[12];

int p0 = 10;
int p1 = 11;
int p2 = 12;
int p3 = 13;

unsigned offset = 0;

copy_data(arr0, offset, p0, p1, p2, p3);

offset = 0;
copy_data(arr1, offset, p0, p1, p2);

printf_data(arr0, 16);
printf_data(arr1, 12);

delete [] arr1;
delete [] arr0;
return 0;
}

更新:更正的功能

template <typename T>
void copy_data(unsigned char* ar, unsigned& offset, T data) {
std::memcpy(ar + offset, (void*)&data, sizeof(data));
offset += sizeof(data);
}

template <typename T, typename... Args>
void copy_data(unsigned char* ar, unsigned& offset, T data, Args... args) {
copy_data(ar, offset, data);
copy_data(ar, offset, args...);
}

最佳答案

递归仅在以下情况下输出任何内容:

if ((sizeof...(Args))==0) {
copy_data(ar, offset, data);
}

这只会在您去除除最后一个参数之外的所有参数之后发生。

删除 if 子句。

关于c++ - 带递归的可变参数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52291366/

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