EDIT: Before we begin, this question is not about proper usage of std::initializer_list
; it is about what should be passed when the convenient syntax is desired. Thank you for staying on topic.
C++11 introduces std::initializer_list
to define functions accepting braced-init-list arguments.
struct bar {
bar( char const * );
bar( int );
} dog( 42 );
fn foo( std::initializer_list< bar > args );
foo( { "blah", 3, dog } );
The syntax is nice, but under the hood it is distasteful due to various problems:
They cannot be meaningfully moved. The above function must copy
dog
from the list; this cannot be converted to move-construction or elided. Move-only types cannot be used at all. (Well,const_cast
would actually be a valid workaround. If there's an article about doing so, I'd like to see it.)There are no
constexpr
semantics, either. (This is forthcoming in C++1y. It's a minor issue, though.)const
does not propagate as it does everywhere else; theinitializer_list
is neverconst
but its contents always are. (Because it doesn't own its contents, it cannot give write access to a copy, although copying it anywhere would seldom be safe.)The
initializer_list
object does not own its storage (yikes); its relationship to the completely separate naked array (yikes) providing the storage is hazily defined (yikes) as the relationship of a reference to a bound temporary (quadruple yikes).
I have faith these things will be fixed in due time, but for now is there a best practice to get the advantages without hard-coding to initializer_list
? Is there any literature about or analysis into working around direct dependency on it?
The obvious solution is to pass by value a standard container such as std::vector
. Once the objects are copied into it from the initializer_list
, it is move-constructed to pass by value, and then you can move the contents out. An improvement would be to offer storage on the stack. A good library might be able to offer most of the advantages of initializer_list
, array
, and vector
, without even using the former.
Any resources?