繁体   English   中英

将大括号初始化程序完美转发给构造函数?

[英]Perfect forwarding of a braced initializer to a constructor?

有类似的问题,但似乎没有一个是这样的。

我有一个用于保存S的包装器 class 。 以最简单的形式,我们有

// 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)...) {}
};

当我调用WrappedSSimple({1,2})时,这似乎有效。 但是,我想将 c'tor 设为私有并拥有 static 工厂 function。 那失败了:

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 function 来完美地推进大括号?

在您的第一个示例WrappedSSimple({1,2})正在调用WrappedSSimple的移动构造函数,其中一个临时构造函数是通过用户定义的构造函数作为参数构造的。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM