[英]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.