C ++ 11 constexpr构造函数如何从指针完全初始化C样式的数组?

问题描述 投票:0回答:1

在c ++ 11中,我希望具有如下结构:

template<unsigned n> struct bytes_block {
    char data[n];
    constexpr bytes_block(char const *s):data(....) {}
};

可以安全地假设构造函数参数s指向一个内存区域,从该区域开始至少可以复制n个连续字符,而无需调用构造函数中的任何UB。

但是,我不知道如何填写...。

是否可以为bytes_block构造函数构造一个constexpr实现,该实现符合C ++ 11?可以创建任意数量的其他constexpr函数以用作帮助程序,只要它们当然仅包含单个return语句即可。

c++ arrays c++11 constexpr
1个回答
0
投票

您可以通过使用std::make_index_sequence<n>中的参数包建立索引来完成此操作。当然,这在C ++ 11中不存在,但是实现起来很容易:

std::make_index_sequence<n>

然后,构造函数变得很简单,就像委派获取包并为其编制索引一样:

#include <cstddef>
#include <utility>

// Use `std::index_sequence` if available, otherwise implement it.
namespace detail {
#if __cplusplus < 201300L
    // There are probably better implementations of this out there
    template<std::size_t... Ints>
    struct index_sequence {};

    template<std::size_t Target, std::size_t... Ints>
    struct make_index_sequence_helper;

    template<>
    struct make_index_sequence_helper<static_cast<std::size_t>(-1)> {
        using type = index_sequence<>;
    };

    template<std::size_t... Current>
    struct make_index_sequence_helper<0, Current...> {
        using type = index_sequence<0, Current...>;
    };

    template<std::size_t... Current, std::size_t Last>
    struct make_index_sequence_helper<Last, Current...> {
        using type = typename make_index_sequence_helper<Last - 1u, Last, Current...>::type;
    };

    template<std::size_t N>
    using make_index_sequence = typename make_index_sequence_helper<N - 1u>::type;

#else
    using std::index_sequence;
    using std::make_index_sequence;
#endif
}
© www.soinside.com 2019 - 2024. All rights reserved.