c++ - 在工厂类中存储和传递参数包
问题描述
我正在尝试编写一个“工厂”类模板,其实例化具有可变参数构造函数,这些构造函数将它们的参数存储在一个元组中,然后将这些参数传递给工厂创建的对象的构造函数。
一个最小的例子可能会更清楚:
#include <memory>
#include <tuple>
struct Foo
{
Foo(int arg1, double arg2)
{}
// ...
};
template<typename T, typename ...ARGS>
class Factory
{
public:
Factory(ARGS&&... args)
: _stored_args(std::make_tuple(std::forward<ARGS>(args)...))
{}
std::unique_ptr<T> create()
{ return std::apply(std::make_unique<T>, _stored_args); }
private:
std::tuple<ARGS...> _stored_args;
};
template<typename T, typename ...ARGS>
std::unique_ptr<Factory<T, ARGS...>> make_factory(ARGS&&... args)
{ return std::make_unique<Factory<T, ARGS...>>(std::forward<ARGS>(args)...); }
int main()
{
auto foo_factory(make_factory<Foo>(1, 2.0));
auto foo_ptr(foo_factory->create());
// ...
}
我的问题是调用std::apply
显然是错误的,因为 gcc 和 clang 都抱怨no matching function for call to '__invoke'
. 我在这里做错了什么?
解决方案
您需要做的就是将std::make_unique
调用包装成一个完美转发的 lambda:
std::unique_ptr<T> create() {
return std::apply(
[](auto&&... xs) {
return std::make_unique<T>(std::forward<decltype(xs)>(xs)...);
},
_stored_args);
}
原因是它std::make_unique
不仅需要一个T
模板参数,而且还需要Args...
,在这种情况下,它是由 fowarding 推导出来的xs...
。请参阅cppreference。
推荐阅读
- draw.io - Draw.io - 如何使用命令行将所有选项卡导出到图像
- javascript - 将用户输入存储在本地存储中的特定数组中
- android - 使用 Firestore 中的 where 子句过滤并获取所有子集合
- javascript - 使用 Javascript 在 Datepicker 中禁用以前的日期
- c# - 上传大文件 Azure Blob .net SDK v12 问题
- html - 如何处理手机中的图像纵横比
- java - 提取 map(...) 调用中的代码
- scala - akka 流物化值使用不同的选项
- google-cloud-platform - 有没有办法不仅可以在 GCP 中打开 windows 实例,还可以登录到特定的用户帐户?
- php - 在PHP中查询一个大的MySql表效率?