我正在為嵌入式平臺(一個 ATTiny,盡管我認為這并不重要)開發一些 C 代碼,這些代碼奇跡般地可以用 C 17 編譯。我試圖在constexpr任何可能的地方使用和模板引數,以避免手動管理陣列大小,同時避免記憶體分配,同時還產生一些難以表達無效狀態的東西,以防同事以后需要修改它。
我有一個特定的資料型別,它需要能夠存盤可變數量的值(在源代碼中不同,而不是在運行時),這些值將在運行時迭代。使用模板陣列constexpr大小技巧和模板引數,我可以定義一個帶有初始化串列的陣列,然后將其傳遞給使用模板大小引數構造的物件,如下所示:
template <typename T, size_t n>
constexpr size_t array_size(const T (&)[n]) { return n; }
uint16_t data_fast_flash[] = { 100, 400 };
LedPattern<array_size(data_fast_flash)> fast_flash{data_fast_flash};
uint16_t data_slow_flash[] = { 100, 900 };
LedPattern<array_size(data_slow_flash)> slow_flash{data_slow_flash};
uint16_t data_double_flash[] = { 100, 200, 100, 1000 };
LedPattern<array_size(data_double_flash)> double_flash{data_double_flash};
該LedPattern課程如下,但我不確定它是否相關:
template <size_t N>
class LedPattern : public ILedPattern {
public:
explicit LedPattern(uint16_t* delay) : delay_(delay), count_(N) {}
void reset() override { index_ = 0; };
[[nodiscard]] uint16_t current() const override { return *(delay_ index_); }
void next() override {
if ( index_ >= count_) index_ = 0;
};
private:
uint16_t* delay_;
size_t count_;
size_t index_{};
};
以上所有內容都按預期作業,但我希望將定義壓縮到uint16_t陣列的創建和命名可以消失的地方,因為我認為它們現在是設定中最容易出錯的部分。
我確實找到了一些看似相關的解決方案,但它們都依賴于我在這個平臺上沒有的標準庫,例如一個usingstd::index_sequence,另一個 using std::forward。
使用 C 17 但沒有標準庫,是否有某種方法可以構造與模板功能相似的東西:
- 只需要某種初始值設定項串列
- 最好可以推斷出值串列本身的元素數量
- 在運行時不需要任何分配
大致類似于以下內容,盡管我不依賴于這種確切的語法,并且我在LedPattern內部更改作業方式也沒有問題:
LedPattern fast_flash{100, 400};
LedPattern slow_flash{100, 900};
LedPattern double_flash{100, 200, 100, 1000};
uj5u.com熱心網友回復:
這似乎是用戶定義演繹指南的作業。您可以執行以下操作:
#include <concepts>
#include <cstddef>
#include <cstdint>
using std::size_t;
using std::uint16_t;
template<size_t N>
class LedPattern {
public:
template<typename ...D>
explicit LedPattern(D...d) : delay_{uint16_t(d)...}, count_(N) {}
private:
uint16_t delay_[N];
size_t count_;
size_t index_{};
};
template<std::convertible_to<uint16_t> ...D>
LedPattern(D...) -> LedPattern<sizeof...(D)>;
LedPattern pat{100, 200, 300};
如果您的編譯器還不支持概念,只需替換std::convertible_to<uint16_t>為。typename
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/496356.html
上一篇:帶有少量引數的模板函式的推導
