1
我想在可變參數函數中構造一個由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);
}
但是有沒有一種更簡單的方式,不依靠這種額外的類型?