Reputation: 657
I have a problem with the following code
template<typename... TArgs>
void SomeFunc() {
Foo* data[] = {
Func<TArgs>()..., // <- expand the pack into array but calling Func for each type
nullptr
};
}
Func of course returns Foo* instance.
The nullptr at the end is for the case if TArgs is empty so that the array has size is never zero but despite this fact when compiling the code and instantiating SomeFunc with empty template argument list I get:
cannot allocate an array of constant size 0
like the nullptr element was never there. If I change the declaration of the array to:
Foo* data[sizeof...(TArgs) + 1] =
The error message changes too:
Error 2 error C4789: buffer 'data' of size 8 bytes will be overrun; -4 bytes will be written starting at offset 8
What am I missing ? If someone could please enlighten me because I am clearly hammering this problem for too long and probably don't see the main issue here.
Upvotes: 1
Views: 1673
Reputation: 56863
Just another attempt to find a work-around (too long for a comment, so I'll just post it as an answer):
struct FooNull {};
template<typename T> Foo* FuncWrapper() { return Func<T>(); }
template<> Foo* FuncWrapper< FooNull >() { return nullptr; }
template<typename... TArgs>
void SomeFuncImpl() {
Foo* data[] = {
FuncWrapper<TArgs>()...
};
}
template<typename... TArgs>
void SomeFunc() {
SomeFuncImpl<TArgs...,FooNull>();
}
Upvotes: 2