Variadic function with recursion
Variadic function with recursion
I trying to write a recursive function with variadic parameters for copy my data. But this function copy only last parameter. What I do wrong?
This is output:
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
Best regards.
#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;
UPDATE: corrected function
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...);
@Jarod42 Yeees of course! But in this case it doesn't matter.
– Max
Sep 12 '18 at 14:16
1 Answer
1
The recursion only outputs anything when:
if ((sizeof...(Args))==0)
copy_data(ar, offset, data);
and that only happens after you strip every argument except the last off.
Remove the if
clause.
if
Thank you, Adam. It worked 10 0 0 0 11 0 0 0 12 0 0 0 13 0 0 0 n 10 0 0 0 11 0 0 0 12 0 0 0
– Max
Sep 12 '18 at 9:10
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Note also that your output depends of endianess.
– Jarod42
Sep 12 '18 at 14:14