[英]How would one call std::forward on all arguments in a variadic function?
[英]No matching function for call std::forward(const std::string &) with variadic arguments
我試圖將一個可移動的包裝器設置為不可復制的,不可移動的類,但是我將const std::string
變量傳遞給構造const std::string
遇到了問題。 下面的最小示例產生以下錯誤:
#include <iostream>
#include <memory>
#include <string>
#include <utility>
struct X {
std::string x;
X(const std::string &x) : x(x) {}
X(const X &x) = delete;
X(X &&x) = delete;
};
struct Wrapper {
std::unique_ptr<X> x;
Wrapper(const Wrapper & wrapper) = delete;
Wrapper(Wrapper && wrapper) = default;
template<typename... Args>
Wrapper(Args&&... args) : x(std::make_unique<X>(std::forward(args)...)) {}
};
int main() {
const std::string XXX = "XXX";
Wrapper w{XXX};
std::cout << w.x->x << std::endl;
}
錯誤信息:
forwarding.cc:21:53: error: no matching function for call to 'forward'
Wrapper(Args&&... args) : x(std::make_unique<X>(std::forward(args)...)) {}
^~~~~~~~~~~~
forwarding.cc:26:13: note: in instantiation of function template specialization 'Wrapper::Wrapper<const std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > &>' requested here
Wrapper w{XXX};
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.2.0/../../../../include/c++/7.2.0/bits/move.h:73:5: note: candidate template ignored: couldn't infer template argument '_Tp'
forward(typename std::remove_reference<_Tp>::type& __t) noexcept
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.2.0/../../../../include/c++/7.2.0/bits/move.h:84:5: note: candidate template ignored: couldn't infer template argument '_Tp'
forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
^
1 error generated.
您需要將模板參數顯式傳遞給std::forward
:
std::forward<Args>(args)...
這是因為std::forward
需要某種方式來了解args...
的“原始值類別” args...
這是不可能通過模板參數推導單獨進行的,因為args
總是一個左值。
Lvalues將在轉發引用的模板參數推導的上下文中推斷為左值引用 (作為特殊規則),因此std::forward
可以通過查看Args...
內部的類型來完成它的工作Args...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.