jeudi 27 décembre 2018

Lvalue no matching (&&) without template, but matching (T &&) with template?

#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;
}

Can be compiled.

#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;
}

I replace T to string, the code can not be compiled.

error:

❯ 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) {
          ^

I'm so confused.

Aucun commentaire:

Enregistrer un commentaire