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);
}
但是有没有一种更简单的方式,不依靠这种额外的类型?