Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array's initialization body as function parameter (C-array), is it possible?

Tags:

I am searching for some help in next situation:
I have some class and some method in it, syntax is like this:

class SomeClass {       public:               void doSomething(int *a);   }; 

So I want to call this method like

SomeClass::doSomething({ 0, 1, 2, 3, 4 }); 

Is it possible in any language? Any (C++, C, obj-c, obj-c++) implementation is welcome! I know that this initialization block is a body of array, like

int *a = { 0, 1, 2, 3, 4 }; SomeClass::doSomething(a); 

But interface will look great, I think, if there will be no temp variables before function calls (as we don't need to know the type of parameter in class-client). So, is there any chance to make this?

like image 331
art-divin Avatar asked Oct 05 '11 07:10

art-divin


2 Answers

In C99 this works:

functionThatTakesIntPtrOrArray( (int []){ 1, 2, 3, 4 } ); 

..and similar things can be done with structs.

like image 110
Dmitri Avatar answered Oct 13 '22 13:10

Dmitri


This is about C++11 initializer lists (section 18.9).

void foo (std :: initializer_list <int> inputs) {     for (auto i : inputs) {         // ...     } }  foo ({10, 20, 30}); 

Only the compiler can create an initializer list, but you can treat it like a standard STL-style container with begin(), end(), size(), and random-access iterators.

std::vector (and I expect some other containers) can now be constructed with initializer lists, so

std :: vector <std :: string> foo {"a", "b"}; 

is equivalent to

std :: vector <std :: string> foo; foo .push_back ("a"); foo .push_back ("b"); 

except that it may perform fewer allocations. Note that the const char* have been turned into std::string automagically.

like image 22
spraff Avatar answered Oct 13 '22 13:10

spraff