I saw some valid template code as below:
template<typename R, typename P, size_t N, size_t... I>
constexpr array<R, N> to_array_impl(P (&a)[N], std::index_sequence<I...>) noexcept
{
return { {a[I]...} };
}
Well, what does the double brace mean here? When do we need to use double brace(I'm using c 17 now), I guess it's restricted to return
statement?
I also see code like below, that there's function call inside double braces:
template<typename R, typename P, size_t N, size_t... I>
constexpr array<R, N> to_array_impl(P (&&a)[N], std::index_sequence<I...>) noexcept
{
return { {move(a[I])...} };
}
So what's the difference here between using one brace and two braces?
Thanks!
CodePudding user response:
Double brace initialization is only supported in C 11
and later. In earlier versions of C
, you would need to use a different method to achieve the same effect. Double braces are used to create a list initialization of an object. This can be used to initialize an object with a brace-enclosed list of elements, where the elements are either copy-initialized from the corresponding list element or are direct-initialized if the element has a direct initializer.
template<typename R, typename P, size_t N, size_t... I>
constexpr array<R, N> to_array_impl(P (&a)[N], std::index_sequence<I...>) noexcept
{
return { {a[I]...} };
}
Here, double braces are used to create a list initialization of an array
object. The elements of the array are copy-initialized from the corresponding elements of the input array a
. The std::index_sequence
is used as a compile-time sequence of integers, and the ...
operator is used to unpack the sequence and expand it into a comma-separated list of elements.
For second code
template<typename R, typename P, size_t N, size_t... I>
constexpr array<R, N> to_array_impl(P (&&a)[N], std::index_sequence<I...>) noexcept
{
return { {move(a[I])...} };
}
Here , the double braces are used to create a list initialization of an array
object. The elements of the array are direct-initialized with the result of calling move
on the corresponding elements of the input array a
. The std::index_sequence
and ...
operator are used in the same way as in the first example.
Double braces
can be more expensive, as it requires an extra assignment operation.
CodePudding user response:
When do we need to use double brace(I'm using c 17 now), I guess it's restricted to return statement?
The double braces are not require in your given example. Just surrounding the pack expansion with one set of braces is enough.
So what's the difference here between using one brace and two braces?
In your given example, adding double braces have no additional effect. That is, using single set of braces is equivalent to using double braces(in the given example).