簡體   English   中英

在可變參數模板中構造固定大小的數組

[英]Construct fixed-size array in variadic template

我想在可變函數中構造8個整數的數組。 沒問題:

template <typename... Ints>
void foo(Ints... ints) {
    static_assert(sizeof...(Ints) < 8, "some useful error");

    const int my_array[8] = {ints...};
}

即使自動歸零也會初始化數組,因此,如果我調用foo(1, 2, 3)我將得到一個{1, 2, 3, 0, 0, 0, 0, 0}類的數組。

現在,如果我想默認為非零值怎么辦? 就像-1。 這有效:

template <int Def>
struct Int {
    Int() : val(Def) { }
    Int(int i): val(i) { }

    inline operator int() const { return val; }

    int val;
};

template <typename... Ints>
void foo(Ints... ints) {
    const Int<-1> my_array_def[8] = {ints...};
    const int* my_array = reinterpret_cast<const int*>(my_array_def);
}

但是,有沒有更簡單的方法不依賴於這種額外類型呢?

只需使用另一個模板:

template <typename... Ints>
auto foo(Ints... ints) -> typename std::enable_if<sizeof...ints==8>::type {
    const int my_array[] = {ints...};
}
template <typename... Ints>
auto foo(Ints... ints) -> typename std::enable_if<sizeof...ints<8>::type {
    return foo(ints..., -1);
}

暫無
暫無

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

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