左右值3
void test(string &tmp) // lvalue
{
dout<<"string& fun:"<<tmp<<endl;
}
template<typename T>
void test(T& para, typename std::enable_if<std::is_same<T, const std::string>::value>::type * = 0) // const lvalue, const rvalue
{
dout<<" template T&:"<<para<<endl;
}
void test(string &&tmp) // lvalue
{
dout<<"string&& fun:"<<tmp<<endl;
}
string one("foo");
const string two("bar");
string three()
{
return "three";
}
const string four()
{
return "four";
}
int main()
{
test(one);
test(two);
test(four());
test(three()); //error how do it ? in c++ 03
}
g++ tpl.cpp -std=c++11 -g -fno-elide-constructors -O0
输出:
[tpl.cpp:134:test]|string& fun:foo
[tpl.cpp:139:test]| template T&:bar
[tpl.cpp:139:test]| template T&:four
[tpl.cpp:143:test]|string&& fun:three
首先:
void test(string &tmp) 函数参数是string &类型,说明tmp是可以修改,所以肯定不能传const 左值,const 右值,右值(临时对象),因为这三类都是不可修改的.能传入的只有string左值.
template<typename T>
void test(T& para, typename std::enable_if<std::is_same<T, const std::string>::value>::type * = 0) 中T被推导成const std::string才有效,因此参数类型是const string &.这样就可以处理const 左值,
const 右值.