将一个有支撑的初始值设定项完美地转发到构造函数

Perfect forwarding of a braced initializer to a constructor?

本文关键字:完美 构造函数 转发 一个      更新时间:2024-09-23

也有类似的问题,但似乎都不是这样。

我有一个包装器类,它的存在是为了保存S。在最简单的形式中,我们有

// A simple class with a two-argument constructor:
struct S {
int x[2];
S(int x, int y) : x{x, y} {}
};
struct WrappedSSimple {
S s;
template <typename... Args>
WrappedSSimple(Args&&... args) : s(std::forward<Args>(args)...) {}
};

当我调用CCD_ 2时,它似乎起作用。然而,我想让c'tor私有化,并拥有一个静态工厂函数。失败:

struct WrappedS {
S s;
template <typename... Args>
static WrappedS make(Args&&... args) { return WrappedS(std::forward<Args>(args)...); }
private:
template <typename... Args>
WrappedS(Args&&... args) : s(std::forward<Args>(args)...) {}
};

带有

<source>:28:14: error: no matching function for call to 'make'
auto w = WrappedS::make({1,2}); // This is not.
^~~~~~~~~~~~~~
<source>:19:21: note: candidate template ignored: substitution failure: deduced incomplete pack <(no value)> for template parameter 'Args'
static WrappedS make(Args&&... args) { return WrappedS(std::forward<Args>(args)...); }
^

https://godbolt.org/z/rsWK94Thq

有没有一种方法可以通过staticmake函数完美地转发大括号?

在第一个示例中,WrappedSSimple({1,2})调用WrappedSSimple的move构造函数,并将通过用户定义的构造函数构造的临时构造函数作为参数。

如果构造函数是私有的,则不能用工厂复制此行为,因为需要访问构造函数的临时对象总是在调用方的上下文中创建的。

通常也不能转发非类型大括号。如果可以将大括号的每个元素的类型限制为相同,那么最好使用std::initializer_list或对数组的引用作为make的参数。