【问题标题】:Lvalue no matching (&&) without template, but matching (T &&) with template?左值不匹配(&&)没有模板,但匹配(T &&)与模板?
【发布时间】:2018-12-27 08:35:32
【问题描述】:
#include <bits/stdc++.h>
using namespace std;

template<class T = string>
void f(T &&s) {
    cout << s << endl;
}

int main() {
    string s("1234");
    f(s);
    f("1234");

    return 0;
}

可以编译。

#include <bits/stdc++.h>
using namespace std;

void f(string &&s) {
    cout << s << endl;
}

int main() {
    string s("1234");
    f(s);
    f("1234");

    return 0;
}

我把T替换成string,代码编译不出来。

错误:

❯ g++-8 -std=c++11 a.cpp && ./a.out
a.cpp: In function 'int main()':
a.cpp:10:11: error: cannot bind rvalue reference of type 'std::__cxx11::string&&' {aka 'std::__cxx11::basic_string<char>&&'} to lvalue of type 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'}
         f(s);
           ^
a.cpp:4:10: note:   initializing argument 1 of 'void f(std::__cxx11::string&&)'
     void f(string &&s) {
          ^

我很困惑。

【问题讨论】:

  • 查找“转发参考”。 T&amp;&amp; 在这里不被视为std::string&amp;&amp;
  • 谢谢,所以T 的类型是std::string &amp;,然后是std::string &amp; &amp;&amp; -> std:string &amp;
  • X &amp;&amp; 只会在 X 是已知类型时绑定到右值。但是对于模板,T &amp;&amp; 是一个转发引用,将根据推导的类型变为X &amp;&amp;X &amp;X const &amp;

标签: c++ c++11 lvalue


【解决方案1】:

模板类型推断有一些例外。 如果函数模板接收到一个右值引用并且我们传入了一个左值引用,编译器会将其推断为一个左值引用。这就是 std::move 正常工作的原因。

template <typename T>
typename remove_reference<T>::type&& move(T&& t)
{
    return static_cast<typename remove_reference<T>::type&&>(t);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 2022-08-16
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多