Reputation: 1
I want to have initializer_list as a parameter in my function in order to use an undetermined amount of a specific type of variable. It must be a initializer_list because I want to be able to create the list on the function call and because I pass the list into other subfunctions. However, I need to be able to modify the elements in the list and I can't because initializer_list automaticly makes the pointers of type const.
So my question is how do I go about making my own initializer_list class? Making a copy of the header with const removed didn't work and I can't seem to find the answer anywhere.
Upvotes: 0
Views: 870
Reputation: 461
You can't do this directly. However, I did kind of workaround in my code sometime ago.
First, a slice
type which is a non-owning wrapper around contiguous chunk of memory - a pointer to its start and its size.
Second, I added following ctor:
slice(std::initializer_list<T> && list)
: slice((T*)list.begin(), list.size())
{ }
where T is slice's type. This works well on G++ 4.8 and 4.9, though I didn't check it on 5.X versions.
This is definitely a hack, but you'll be able to use slice<T>
as function argument, and then (with enough variety of implicit constructors) pass any contiguous container there, including array
, vector
and initializer_list
. With full support for moves.
Hope this helps.
Upvotes: 0
Reputation: 2241
I think you might be able to just use a vector.
void foo(std::vector<int> values);
is callable with
foo({ 1, 2, 3, 4 });
and then you can pass (move) the vector around as usual and the elements are modifyable of course.
Upvotes: 3
Reputation: 171333
You can't. std::initializer_list
is a magic type that is intricately tied to the compiler, and there is no way to create your own type with the same ability to be constructed from a braced-init-list.
In that sense it's a bit like std::typeinfo
and std::nullptr_t
. They happen to be defined in namespace std
and so appear to be part of the standard library, but they are actually predefined types that are part of the run-time environment and cannot be emulated in pure C++.
Upvotes: 3