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...);






Note also that your output depends of endianess.

– Jarod42
Sep 12 '18 at 14:14






@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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế