没有与可变参数调用std :: forward(const std :: string&)的匹配函数

时间:2018-01-29 12:55:29

标签: c++ c++11

我试图将一个可移动的包装器设置为不可复制的,不可移动的类,但是我在将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.

1 个答案:

答案 0 :(得分:12)

您需要将模板参数明确传递给├──container ├──folder ├──file $ curl -i -H "X-Auth-Token: AUTH_tkb26239d441d6401d9482b004d45f7259" https://dal05.objectstorage.softlayer.net/v1/AUTH_df0de35c-d00a-40aa-b697-2b7f1b9331a6/container/folder

std::forward

这是因为std::forward<Args>(args)... 需要某种方式来了解&#34;原始值类别&#34;通过模板参数推导单独作为std::forward的{​​{1}}不可能始终是左值。

Lvalues将在转发引用(作为特殊规则)的模板参数推导的上下文中推断为左值引用,因此args...可以完成其工作通过查看args内的类型。