In C++11, is it possible to do something similar to the following?
template<typename T, size_t N>
void foo(array<T, N> src) { ... }
...
foo({1, 2, 3})
I'm currently running GCC 4.8.
In C++11, is it possible to do something similar to the following?
template<typename T, size_t N>
void foo(array<T, N> src) { ... }
...
foo({1, 2, 3})
I'm currently running GCC 4.8.
You could use an initializer list directly to achieve that syntax. e.g.:
or make it more generic:
Apparently not. The standard (14.8.2.5) calls this an non-deduced context;
EDIT: You can make the same thing work with
std::vector
, if you just use aninitializer_list
overload to make the deduction of the type work;...but sadly, since the size of
initializer_list
is not a template argument, I can't think of a way to make it deduce and forward the array size from theinitializer_list
in the same way as the type.Yes, I managed to get the following work (since you allow something similar):
Here is how:
I have tested this with gcc 4.7.2 and with clang 3.4 (trunk 184647), they work as expected.
Here is an online version at Stacked-Crooked. However, this code fails to compile at Ideone. Since I was unable to figure out the options passed to the compiler at Ideone, I've given up on that site.
I have shamelessly stolen the
make_array
function from @Pavel Minaev's answer to the How to emulate C array initialization “int arr[] = { e1, e2, e3, … }” behaviour with std::array? question. The othermake_array
suggestions caused compile errors that I couldn't fix.This
make_array
function has limitations, please read the entire post; in particular the discussion std::array - if only it knew its size on comp.lang.c++.moderated is referenced. Apparently, getting a reasonablemake_array
is quite tricky. I wouldn't recommend the simple-mindedmake_array
in this answer to be used in production code.You wouldn't have any problems if the size was a template argument to
std::initializer_list
. Hence the question Why is the size not a template argument of std::initializer_list?