简体   繁体   English

如何初始化 std::array<T, n> 如果 T 不是默认可构造的,那么优雅吗?

[英]How to initialize std::array<T, n> elegantly if T is not default constructible?

How do I initialize std::array<T, n> if T is not default constructible ?如果 T 不是默认可构造的,如何初始化std::array<T, n>

I know it's possible to initialize it like that:我知道可以像这样初始化它:

T t{args};
std::array<T, 5> a{t, t, t, t, t};

But n for me is template parameter:但对我来说n是模板参数:

template<typename T, int N>
void f(T value)
{
    std::array<T, N> items = ??? 
}

And even if it wasn't template, it's quite ugly to repeat value by hand if n is too large.即使它不是模板,如果n太大,手动重复值也是相当难看的。

Given N, you could generate a sequence-type called seq<0,1,2,3,...N-1> using a generator called genseq_t<> , then do this:给定 N,您可以使用名为genseq_t<>的生成器生成名为seq<0,1,2,3,...N-1>的序列类型,然后执行以下操作:

template<typename T, int N>
void f(T value)
{
     //genseq_t<N> is seq<0,1,...N-1>
     std::array<T, N> items = repeat(value, genseq_t<N>{});
}

where repeat is defined as:其中repeat定义为:

template<typename T, int...N>
auto repeat(T value, seq<N...>) -> std::array<T, sizeof...(N)> 
{
   //unpack N, repeating `value` sizeof...(N) times
   //note that (X, value) evaluates to value
   return {(N, value)...}; 
}

And the rest is defined as:其余的定义为:

template<int ... N>
struct seq
{
   using type = seq<N...>;

   static const std::size_t size = sizeof ... (N);

   template<int I>
   struct push_back : seq<N..., I> {};
};

template<int N>
struct genseq : genseq<N-1>::type::template push_back<N-1> {};

template<>
struct genseq<0> : seq<> {};

template<int N>
using genseq_t = typename genseq<N>::type;

Online demo在线演示

Hope that helps.希望有帮助。

Sadly the existing answers here don't work for non-copyable types.遗憾的是,这里的现有答案不适用于不可复制的类型。 So I took @Nawaz answer and modified it:所以我接受了@Nawaz 的回答并对其进行了修改:

#include <utility>
#include <array>


template<typename T, size_t...Ix, typename... Args>
std::array<T, sizeof...(Ix)> repeat(std::index_sequence<Ix...>, Args &&... args) {
   return {{((void)Ix, T(args...))...}};
}

template<typename T, size_t N>
class initialized_array: public std::array<T, N> {
public:
    template<typename... Args>
    initialized_array(Args &&... args)
        : std::array<T, N>(repeat<T>(std::make_index_sequence<N>(), std::forward<Args>(args)...)) {}
};

Note that this is an std::array subclass so that one can easily write请注意,这是一个std::array子类,因此可以轻松编写

class A { 
    A(int, char) {}
}

...

class C {
    initialized_array<A, 5> data;

    ...

    C(): data(1, 'a') {}
}

Without repeating the type and size.无需重复类型和大小。 Of course, this way can also be implemented as a function initialize_array .当然,这种方式也可以实现为函数initialize_array

Following will solve your issue:以下将解决您的问题:

#if 1 // Not in C++11, but in C++1y (with a non linear better version)

template <std::size_t ...> struct index_sequence {};

template <std::size_t I, std::size_t ...Is>
struct make_index_sequence : make_index_sequence<I - 1, I - 1, Is...> {};

template <std::size_t ... Is>
struct make_index_sequence<0, Is...> : index_sequence<Is...> {};

#endif

namespace detail
{
    template <typename T, std::size_t ... Is>
    constexpr std::array<T, sizeof...(Is)>
    create_array(T value, index_sequence<Is...>)
    {
        // cast Is to void to remove the warning: unused value
        return {{(static_cast<void>(Is), value)...}};
    }
}

template <std::size_t N, typename T>
constexpr std::array<T, N> create_array(const T& value)
{
    return detail::create_array(value, make_index_sequence<N>());
}

So test it:所以测试一下:

struct NoDefaultConstructible {
    constexpr NoDefaultConstructible(int i) : m_i(i) { }
    int m_i;
};

int main()
{
    constexpr auto ar1 = create_array<10>(NoDefaultConstructible(42));
    constexpr std::array<NoDefaultConstructible, 10> ar2 = create_array<10>(NoDefaultConstructible(42));

    return 0;
}

Inspired by @Nawaz, this is more concise and makes better use of the standard: https://godbolt.org/z/d6a7eq8T5受@Nawaz 启发,这更简洁,更好地利用了标准: https ://godbolt.org/z/d6a7eq8T5

#include <array>
#include <type_traits>

#include <fmt/format.h>
#include <fmt/ranges.h>

// Inspired by https://stackoverflow.com/a/18497366/874660 

//! Return a std::array<T, Sz> filled with
//! calls to fn(i) for i in the integer sequence:
template <typename Int, Int...N, typename Fn>
[[nodiscard]] constexpr auto transform_to_array(std::integer_sequence<Int, N...>, Fn fn) {
   return std::array{(static_cast<void>(N), fn(N))...}; 
}

//! Repeated application of nullary fn:
template <std::size_t N, typename Fn>
[[nodiscard]] constexpr auto generate_n_to_array(Fn fn) -> std::array<decltype(fn()), N> {
    return transform_to_array(std::make_integer_sequence<std::size_t, N>(), [&](std::size_t) { return fn(); });
}

int main() {
    static constexpr std::array<int, 3> a = generate_n_to_array<3>([i = 0]() mutable { return 2 * (i++); });
    fmt::print("{}\n", a);    
}

There are already many great answers, so a single remark: most of them use N twice: once in the array<T,N> and once in the repeat/genseq/generate/whatever you call it...已经有很多很好的答案,所以一句话:他们中的大多数人使用N两次:一次在 array<T,N> 中,一次在 repeat/genseq/generate/whatever you call it...

Since we are using a single value anyway, it seems we can avoid repeating the size twice, here's how:由于无论如何我们都使用单个值,看来我们可以避免重复大小两次,方法如下:

#include <iostream>
#include <array>
#include <type_traits>

// Fill with a value -- won't work if apart from non-default-constructible, the type is also non-copyable...
template <typename T>
struct fill_with {
    T fill;
    constexpr fill_with(T value) : fill{value} {}

    template <typename... Args>
    constexpr fill_with(std::in_place_type_t<T>, Args&&... args) : fill{ T{std::forward<Args>(args)...} } {}

    template <typename U, size_t N>
    constexpr operator std::array<U, N> () { 
        return [&]<size_t... Is>(std::index_sequence<Is...>) {
            return std::array{ ((void)Is, fill)... };
        }(std::make_index_sequence<N>{});
    }
};


// A little more generic, but requires C++17 deduction guides, otherwise using it with lambdas is a bit tedious
template <typename Generator>
struct construct_with {
    Generator gen;
    template <typename F> constexpr construct_with(F && f) : gen{std::forward<F>(f)} {}

    template <typename U, size_t N>
    constexpr operator std::array<U, N> () { 
        return [&]<size_t... Is>(std::index_sequence<Is...>) {
            return std::array{ ((void)Is, gen())... };
        }(std::make_index_sequence<N>{});
    }
};

template <typename F>
construct_with(F&&) -> construct_with<F>;


struct A {
    A(int){}
    A(A const&) = delete;
};

int main() {
    std::array<int, 7> arr = fill_with<int>{ 7 };
    std::array<int, 7> arr = fill_with{ 7 }; // Ok since C++17
    // or you can create a maker function to wrap it in pre-c++17 code, as usual.
    std::array<A, 7> as = construct_with{[]{ return A{7}; }};
    for (auto & elem : arr) std::cout << elem << '\n';
}

Note: Here I used a few C++20 constructs, which may or may not be an issue in your case, but changing from one to the other is pretty straight-forward注意:在这里,我使用了一些 C++20 结构,在您的情况下这可能是问题,也可能不是问题,但是从一个更改为另一个非常简单

I'd also recommend using <type_traits> and std::index_sequence and all the other sequence s from the std if possible to avoid reinventing the wheel)如果可能的话,我还建议使用 <type_traits> 和 std::index_sequence 以及 std 中的所有其他sequence ,以避免重新发明轮子)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何初始化std :: array <T, 2> 其中T是不可复制的,非默认可构造的? - How to initialize an std::array<T, 2> where T is non-copyable and non-default-constructible? 是`std :: array <T, 0> `默认可构造的,而`T`不是默认可构造的? - Is `std::array<T, 0>` default constructible where `T` is not default constructible? 初始化std :: array <T,N> 当T不是默认可构造的时,在构造函数初始化器列表中 - Initialization of std::array<T,N> in constructor initializer list when T is not default-constructible 我们可以假设 std::is_default_constructible<t> 和 std::is_constructible<t> 平等吗?</t></t> - Can we assume std::is_default_constructible<T> and std::is_constructible<T> to be equal? std :: is_default_constructible <T> 错误,如果构造函数是私有的 - std::is_default_constructible<T> error, if constructor is private 如何测试一个std :: function <T> 对于模板参数T是可构造的 - How to test if an std::function<T> is constructible for template argument T 如何优雅地初始化std :: atomic数组? - How do I elegantly initialize an array of std::atomic? 如何初始化std :: array的对象 <std::array<T, 2> ,2&gt;? - How do I initialize an object of std::array<std::array<T, 2>, 2>? 标准::承诺<T>在 Visual Studio 2017 中,T 必须是默认可构造的吗? - std::promise<T> where T must be default constructible in Visual Studio 2017? std::vector 类型的数组如何<std::array<T, N> &gt; 或 std::array <std::vector<T> ,N&gt; 存储在内存中? - How are arrays of type std::vector<std::array<T, N>> or std::array<std::vector<T>,N> stored in memory?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM