Initialize an array with another array in member initializer list

126 Views Asked by At

I am writing the constructor for class A below. mutex_array calls the default std::mutex constructor, which is fine. I then want to construct each element of unique_lock_array from each element of std::mutex in the member initializer list. That is, unique_lock_array[i] should be a unique lock for mutex_array[i] before the body of the constructor. Is that possible?

#include <array>
#include <mutex>

class A {
public:
    A() : unique_lock_array(/* ??? */) {}

private:
    std::array<std::mutex, 10> mutex_array;
    std::array<std::unique_lock<std::mutex>, 10> unique_lock_array;
};
1

There are 1 best solutions below

2
NathanOliver On

You need a helper function but that is easy to do now with an immediately executed lambda expression. That would give you

class A {
public:
    A() : unique_lock_array([&]<std::size_t... Is>(std::index_sequence<Is...>)
                            {
                                return std::array{std::unique_lock{mutex_array[Is]}...}; 
                            }(std::make_index_sequence<10>{})) {}

private:
    std::array<std::mutex, 10> mutex_array;
    std::array<std::unique_lock<std::mutex>, 10> unique_lock_array;
};