【发布时间】: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&&在这里不被视为std::string&&。 -
谢谢,所以
T的类型是std::string &,然后是std::string & &&->std:string & -
X &&只会在 X 是已知类型时绑定到右值。但是对于模板,T &&是一个转发引用,将根据推导的类型变为X &&、X &或X const &。