Friday, 15 June 2012

C++ pass array and its length into a function (using macro/inline function?) -



C++ pass array and its length into a function (using macro/inline function?) -

i have been writing c++ little while (java/c long while), wondering if there trick don't know can help me following.

vector<unsigned char> *fromarray(unsigned char data[], int length) { vector<unsigned char> *ret = new vector<unsigned char >(); while (length--) { ret->push_back(*data); } homecoming ret; }

and can utilize so:

unsigned char tmp[] = {0, 1, 2, 3, 4, 5}; vector<unsigned char> *a = fromarray(tmp, sizeof(tmp)); // utilize `a' here

i find pretty cumbersome - i'd write on 1 line

vector<unsigned char> *a = fromarray({0, 1, 2, 3, 4, 5}); // utilize `a' here

is such thing possible? don't have access c++11 unfortunately (looks initializer_list want).

edit

sorry had of fundamentals wrong in here. avoid extending std::vector. think question still valid, illustration bad one.

** potential workaround **

i could define bunch of overloaded functions take different numbers of arguments, eg

vector<unsigned char> *fromarray(unsigned char a) { vector<unsigned char> *ret = new vector<unsigned char >(); ret->push_back(a); homecoming ret; } vector<unsigned char> *fromarray(unsigned char a, unsigned char b) { vector<unsigned char> *ret = new vector<unsigned char >(); ret->push_back(a); ret->push_back(b); homecoming ret; }

but don't think bother...

you can utilize template deduce size of fixed size array:

template< class t, size_t n > auto_ptr<bytearray> foo( t (&data)[n] ) { homecoming auto_ptr<bytearray>(new bytearray(data, n)); }

then

unsigned char tmp[] = {0, 1, 2, 3, 4, 5}; auto_ptr<bytearray> = foo(tmp);

but bear in mind auto_ptr deprecated. prefer unique_ptr. also, note should not publicly inherit std::vector.

c++ arrays macros inline

No comments:

Post a Comment