In his CppCon 2014 talke "Type Deduction and Why You Care", Scott Meyers raises the question why there is a special rule about auto
and braced initializers in the C++11/C++14 standard (his question starts at 36m05s).
The semantic of auto in combination with a braced-init-list is defined in §7.1.6.4/6.
I thought about it and could not come up with a use-case either. The closest thing that I have seen so far is one example where Bjarne Stroustrup used it.
In his Cpp 2014 talk "Make Simple Tasks Simple!", he once uses auto
to capture initializers (but only as a workaround).
Here is the code (part of slide 30, at 37m10s):
// auto ss1 = collect({ 1, 2, 3, 4, 5, 6 }, odd); // error: Bummer!
auto lst = { 1, 2, 3, 4, 5, 6 };
auto ss2 = collect(lst, odd); // {1,3,5}
But note that it is only a workaround. He mentioned that it should not be necessary. Instead he would prefer to directly pass the arguments to the function. So, it cannot really serve as a good motivation for auto
and initializer lists.
My understanding of C++ is not deep enough to judge the downsides of allowing initializer-lists in Bjarne's example, as he proposes. Anyway, it would avoid the need for auto
in that case.
So, is auto
and initializer list only a workaround for something that could have been better solved? Or are there good examples, where the extra auto deduction rule in §7.1.6.4/6 is useful?
Scott Meyers addressed the topic in a blog post: Why auto deduces std::initializer_list for a braced initializer
Like T.C.'s answer, it also refers to N2640. The special deduction rule has been added to allow code like this to work:
In the blog post, Scott cites the following explanation from James Hopkin:
The rationale is in N2640, which wanted to ban deduction of a plain type parameter from a braced initializer list in general:
But carved out a special exception for
auto
: