Re: decltype interaction with initializer lists
Am 07.04.2012 02:55, schrieb Brendan:
Here's some more decltype strangeness. This expression fails to
compile:
decltype({1,2,3})
Here's I'm trying to infer a type of std::initializer_list<int>. Any
idea why this doesn't work? Is this standard or a bug in my compiler
(gcc 4.6)?
This use-case of decltype is not allowed by the core language. Reason is
that decltype requires according to the grammar an /expression/ (see
[dcl.type.simple] p1 for example), but {1, 2, 3} is no expression, it is
a so-called braced-init-list. Note that the support of
braced-init-list's by 'auto' are due to a very special rule. Normal
templates like
template<class T>
void f(T);
don't deduce T if the argument is an braced-init-list like in
f({1,2,3});
So, decltype is consistent with normal templates.
For successful deduction the template argument must have a form like
#include <initializer_list>
template<class T>
void f(std::initializer_list<T>);
Now
f({1,2,3});
can be deduced. This example points to a simple way how to deduce the
proper instantiation of any std::initializer_list's in a generic
context. Just declare a function template like so:
#include <initializer_list>
template<class T>
std::initializer_list<T> create_list(std::initializer_list<T>);
Now use decltype with this helper function template like so:
decltype(create_list({1,2,3}))
In this example the deduced type should be equal to
std::initializer_list<int>.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]