From: Wolfgang Bangerth Date: Mon, 9 Oct 2023 23:15:09 +0000 (-0600) Subject: Allow creation of an ArrayView from a std::initializer_list. X-Git-Tag: relicensing~414^2~4 X-Git-Url: https://gitweb.dealii.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=402017ced127d5a8e474ff72f2f10074314dfe70;p=dealii.git Allow creation of an ArrayView from a std::initializer_list. --- diff --git a/include/deal.II/base/array_view.h b/include/deal.II/base/array_view.h index 684789e32e..4cd48526f7 100644 --- a/include/deal.II/base/array_view.h +++ b/include/deal.II/base/array_view.h @@ -216,6 +216,46 @@ public: template ArrayView(std::array, N> &vector); + /** + * A constructor that creates a view of the array that underlies a + * [std::initializer_list](https://en.cppreference.com/w/cpp/utility/initializer_list). + * This constructor allows for cases such as where one has a function + * that takes an ArrayView object: + * @code + * void f(const ArrayView &a); + * @endcode + * and then to call this function with a list of integers: + * @code + * f({1,2,3}); + * @endcode + * This also works with an empty list: + * @code + * f({}); + * @encode + * + * @note `std::initializer_list` objects are temporary. They are constructed + * where the compiler finds a brace-enclosed list, and so they only live + * for at most the time it takes to execute the current statement. As a + * consequence, creating an ArrayView object of such a `std::initializer_list` + * also results in a view object that points to valid memory only for as long + * as the current statement is executed. You shouldn't expect that the + * resulting ArrayView can be used to point to useful memory content past + * that point. In other words, while this code... + * @code + * std::vector v(10); + * ArrayView a(v); + * f(a); + * @endcode + * ...works because the array `v` pointed to exists until after the call to + * `f()`, the following code will not likely work as expected: + * @code + * ArrayView a({1,2,3}); + * f(a); + * @endcode + */ + ArrayView(const std::initializer_list> + &initializer_list); + /** * Reinitialize a view. * @@ -511,6 +551,16 @@ inline ArrayView::ArrayView( +template +inline ArrayView::ArrayView( + const std::initializer_list> &initializer) + : // use delegating constructor + ArrayView((initializer.size() > 0 ? initializer.begin() : nullptr), + initializer.size()) +{} + + + template inline bool ArrayView::operator==(