![](/img/trans.png)
[英]Why does a T&& parameter preserves the constness and lvalue/rvalue property of the argument while a T& doesn't
[英]Passing an lvalue to rvalue template parameter won't allow me to declare const T& var
只是有关参考折叠的快速查询,这是我的代码:
template<typename B>
void funct(B&& b)
{
const B woi= 10; // ERROR: B is int& , how come it won't let me make const int& var? // If B is int(just incase i am wrong), it still won't work
b = 11;
}
int main(int argc, char** argv) {
int k =10;
funct(k);
std::cout<<k<<std::endl; //prints 11;
return 0;
}
我在玩,并做一些测试。 为什么我不能创建const int& var
其中B是int&
类型?
我再次尝试确保它是int&
,这是代码:
template<typename B> //B will be deducated as B& or int&
void funct2(B&& b){ //receives lvalue refence, param will be B& b
const B p = 5; //ERROR eventhough B is B& or int&
}
int main(int argc, char** argv) {
//make ref
int l = 5;
int & m = l;
funct2(m); //passed an lvalue reference
return 0;
}
问题:它为什么不让我重用int&
作为const
?
编辑:我知道const int&
主要用于左值,但const int & var = 10
可以在main / functions上正常工作,但不能用于B
例:
template<typename B>
void funct(B&& b)
{
const int& p = 10;
//const B woi= 10; gives me errors
}
尽管它们应该是相同的。
问题在于,将const
添加到int&
意味着const引用,而不是对const的引用,即const B
,其中B
是int&
不是 const int&
。 const引用与普通引用相同,因此它不能绑定到右值。
如果在传递左值或右值时都需要const int&
,则可以执行以下操作:
const std::remove_reference_t<B>& woi; //c++14
const typename std::remove_reference<B>::type& woi; //c++11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.