将一个有支撑的初始值设定项完美地转发到构造函数
Perfect forwarding of a braced initializer to a constructor?
也有类似的问题,但似乎都不是这样。
我有一个包装器类,它的存在是为了保存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
有没有一种方法可以通过static
make
函数完美地转发大括号?
在第一个示例中,WrappedSSimple({1,2})
调用WrappedSSimple
的move构造函数,并将通过用户定义的构造函数构造的临时构造函数作为参数。
如果构造函数是私有的,则不能用工厂复制此行为,因为需要访问构造函数的临时对象总是在调用方的上下文中创建的。
通常也不能转发非类型大括号。如果可以将大括号的每个元素的类型限制为相同,那么最好使用std::initializer_list
或对数组的引用作为make
的参数。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 完美的转发和构造函数
- 完美的转发构造函数和已删除的构造函数
- 使用完美转发的模板转换构造函数
- 在类层次结构中,完美的转发构造函数和复制构造函数之间的冲突
- 完美的转发功能与完美的转发构造函数
- C++构造函数:完美的转发和过载
- 临时寿命和完美的转发构造函数
- 如何为类似元组的可变类创建一个完美的转发构造函数
- 如何模板化c++构造函数以实现完美的转发