From: Faisal Vali on
Multiple people (including me) in this newsgroup have opined that it
would be convenient to have a make_array facility that automatically
deduced the type and number of elements to std::array.

In essence, it should not be unreasonable to expect the following to
work:

auto a = make_array({1,2,3}); // array<int,3>
auto ca = make_array({"a", "ab", "abc"}); //array<const char*,3>
auto s = make_array({std::string("a"), "ab", "abc", "abcd"}); //
array<string,4>


In the past, using preprocessor metaprogramming, I had posted a
suboptimal solution that handled the first two but not the third.
http://groups.google.com/group/comp.std.c++/msg/737a87bbc453ceed?hl=en&dmode=source

The standard library also provides a solution (http://www.open-
std.org/
jtc1/sc22/wg21/docs/lwg-closed.html#851) that uses a slightly
different syntax and some creativity to avoid the narrowing problem.


Well here is some code that compiles on gcc 4.5, minimally uses the
preprocessor and provides an adequate solution (whether it is truly
FCD compliant is another issue):

template<class T>
T type_helper(std::initializer_list<T>);

template<class T, int N>
char (&size_helper(const T (&)[N]))[N];

//typedef-alias workaround
template<class T> struct unknown_size_array
{ typedef T type[]; };

// Do type deduction only with first element
#define get_first(first, ...) first }

#define make_array(...) \
std::array< \
decltype(type_helper( \
get_first(__VA_ARGS__))) \
, sizeof(size_helper( \
unknown_size_array< \
decltype( \
type_helper( \
get_first(__VA_ARGS__)))>::type \
__VA_ARGS__)) \
> __VA_ARGS__ \
/**/


The above hinges on the following being valid C++0x code

typedef int UI[];
template<class T, int N> void deduce(const T (&)[N]);
deduce(UI{1,2,3,4,5});

While the above compiles in gcc 4.5, i am not sure that the FCD is
clear on whether it should.
If anyone does know with certainty whether it should or it shouldn't
and can point out the relevant FCD sections to support their claim, I
would surely appreciate it.

Thanks,
Faisal Vali
Radiation Oncology
Loyola


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]