将可变参数模板参数解压缩到数组中,应用每种类型的函数
Unpacking variadic template arguments into array applying function for each type
我对以下代码有问题
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>();
}
相关文章:
- atoi() 在应用于大型命令行参数时会产生不正确的值
- cmake:ExternalProject_Add() 不应用 cmake 参数
- 什么是仅调用一次并调用参数的控制台应用
- WinRT 应用调用 win32 c++ dll 发送参数
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 模板模板参数:以下示例中应用了什么规则
- 将函数应用于元组中的每个元素,将每个元素强制转换为类型包中的不同类型,然后作为参数包传递
- 试图在C++14中将元组应用为参数
- 发生 Qt5.11 应用插件构建错误:信号和插槽参数不兼容
- 模板包扩展以将函数应用于连续的参数对
- 使用参数 + stdout + stderr 从命令行调用 MFC 应用程序
- 由于调用 std::condition_variable 后参数无效而导致应用程序崩溃
- 将 std::bind 应用于带有参数 <boost::asio::ip::tcp::socket> 时出错?
- 如何通过具有通信行参数的procdump启动Windows应用程序?
- 指定在用户固定我的应用程序时用于运行应用程序的命令参数
- 将约束组合应用于参数包
- 如果作为参数传递,请打开文件,否则打开主应用菜单
- 用于将参数应用于函数的模板函数
- C++:将参数应用于函数范围
- 不工作的部分模板参数应用的部分模板专门化