在工厂存储和传递参数包 class
Storing and passing on parameter pack in factory class
我正在尝试编写一个“工厂”class 模板,其实例化具有可变构造函数,这些构造函数将其参数存储在一个元组中,然后将这些参数传递给工厂创建的对象的构造函数。
举一个简单的例子可能会更清楚:
#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
调用包装到 perfect-forwarding 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...
,在本例中是通过转发 xs...
推导出来的。参见 cppreference。
我正在尝试编写一个“工厂”class 模板,其实例化具有可变构造函数,这些构造函数将其参数存储在一个元组中,然后将这些参数传递给工厂创建的对象的构造函数。
举一个简单的例子可能会更清楚:
#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
调用包装到 perfect-forwarding 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...
,在本例中是通过转发 xs...
推导出来的。参见 cppreference。