簡體   English   中英

沒有與可變參數調用std :: forward(const std :: string&)的匹配函數

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM