1

I want to construct an array of 8 integers in a variadic function. No problem:

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

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

That even automatically zero initializes the array, so if I call foo(1, 2, 3) I will get an array like {1, 2, 3, 0, 0, 0, 0, 0}.

Now what if I want to default to something other than zero? Like, say -1. This works:

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);
}

But is there a simpler way that doesn't rely upon having this extra type?

0

1 Answer 1

2

Just use another template:

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.