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?
In C99 this works:
functionThatTakesIntPtrOrArray( (int []){ 1, 2, 3, 4 } );
..and similar things can be done with structs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With