将可变参数模板参数解压缩到数组中,应用每种类型的函数

Unpacking variadic template arguments into array applying function for each type

本文关键字:参数 应用 种类 类型 函数 数组 变参 解压缩      更新时间:2023-10-16

我对以下代码有问题

template<typename... TArgs>
void SomeFunc() {
   Foo* data[] = {
     Func<TArgs>()..., // <- expand the pack into array but calling Func for each type
     nullptr
   };
}

Func 当然返回 Foo* 实例。

最后的 nullptr 适用于 TArgs 为空的情况,因此数组的大小永远不会为零,但尽管如此,在编译代码并使用空模板参数列表实例化 SomeFunc 时,我得到:

cannot allocate an array of constant size 0

就像 nullptr 元素从未存在过一样。如果我将数组的声明更改为:

Foo* data[sizeof...(TArgs) + 1] = 

错误消息也会更改:

Error   2   error C4789: buffer 'data' of size 8 bytes will be overrun; -4 bytes will be written starting at offset 8

我错过了什么?如果有人可以启发我,因为我显然在这个问题上敲打了太久,可能在这里看不到主要问题。

只是寻找解决方法的又一次尝试(太长了,无法发表评论,所以我只将其作为答案发布):

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