首页 > 解决方案 > 高级综合中模板对象数组的编译时创建

问题描述

我正在尝试使用 HLS 来完成此任务,而不是使用“普通”C++,因此大多数库(STL、boost 等)将无法工作,因为它们无法合成(不允许手动内存管理)。我认为这应该可以通过模板元编程实现,但我有点卡住了。

我想创建一个移位寄存器数组,每个移位寄存器都有一个可变的深度。我有 N 个输入,我想创建 N 个移位寄存器,深度为 1 到 N,其中 N 在编译时是已知的。我的移位寄存器类基本上看起来像

template<int DEPTH>
class shift_register{
    int registers[DEPTH];
    ...
};

我尝试遵循并对其进行调整:Programmatically create static arrays at compile time in C++,但是,问题出在最后一行。每个模板化移位寄存器都是不同的类型,因此不能放在一个数组中。但我确实需要一个数组,因为没有办法访问每个移位寄存器。

任何帮助,将不胜感激!

标签: c++templatesmetaprogrammingtemplate-meta-programming

解决方案


每当我听到“编译时间数字序列”时,我都会想std::index_sequence

namespace detail {
    template <typename>
    struct shift_registers;

    template <std::size_t ... Is> // 0, 1, ... N-1
    struct shift_registers<std::index_sequence<Is...> > {
        using type = std::tuple<shift_register<Is + 1>...>;
    };

    template <typename T>
    using shift_registers_t = typename shift_registers<T>::type
}

template <std::size_t N>
using shift_registers = detail::shift_registers_t<std::make_index_sequence<N>>;

推荐阅读