簡體   English   中英

如何使用編譯時信息動態創建模板類?

[英]How to dynamically create templated classes with compile-time information?

我正在使用 SystemC 進行收縮陣列的小型設計。 為此,我實現了一個模板化移位寄存器 class,其中數據類型和延遲是模板。 對於陣列的每一行,我需要附加一個具有不同延遲的移位寄存器,例如,第一行根本沒有延遲,第二行有一個周期延遲,第三行有兩個周期等。為此,我構建了一個在初始化移位寄存器的構造函數中循環。 然后構造函數如下所示:

template<unsigned int HEIGHT, unsigned int WIDTH>
class SystolicArray : public sc_module{
  sc_module shift_registers[HEIGHT];

  SC_CTOR(SystolicArray){
    for(int h = 1; h < HEIGHT; h++){
      shift_registers[h-1] = new ShiftRegister<type, h>
      //Do connections here...
    }
  }
};

現在我面臨的問題是編譯器抱怨我不能像以前那樣在這里使用h (# Error: systolic_array.h(61): error: the value of 'h' is not usable in a constant expression ),我明白為什么會這樣。 但是我構建這個東西所需的所有信息都在編譯時可用,因為它都是從數組的HEIGHTWIDTH模板派生的。 有沒有比我在這里嘗試過的更聰明的方法來做到這一點? 我正在使用 C++11 並且只能使用 SystemC 的可合成子集。

您基本上希望“在編譯時使用不同的h值運行此代碼”。 完美的模板。 你可以用這樣的一對重載來做到這一點:

private:
  template<int h>
  void init(std::integral_constant<int, h>) {
    shift_registers[h-1] = new ShiftRegister<type, h>;
    // Do connections here...

    // Next iteration
    init(std::integral_constant<int, h+1>{});
  }

  void init(std::integral_constant<int, H>) {
    // end when h==H
  }
public:
  SC_CTOR(SystolicArray){
    init(std::integral_constant<int, 1>{});
  }

如果H可以等於0 ,請采取一些預防措施或可能以其他方式編寫。

C++14 具有std::index_sequence (可以在 C++11 中重新實現)

因此,使用delegating 構造函數,它變為:

SC_CTOR(SystolicArray) : SC_CTOR(SystolicArray, std::make_index_sequence<HEIGHT>{})
{}

template <std::size_t... Is>
SC_CTOR(SystolicArray, std::index_sequence<Is...>) :
    shift_registers{new ShiftRegister<type, h + 1>...}
{
    // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM