[英]What's the point of std::remove_reference
Let me dive in C++14 generic lambdas with: 让我深入研究C ++ 14泛型lambdas:
#include <iostream>
// g++ -std=c++14
template<typename T>
T incr(T v)
{
return v + 1;
}
int main()
{
float f = 2.0;
int i = 3;
auto selfincr = [] (auto & value)
{
value = incr<std::remove_reference<decltype(value)>>(value); // A
value = incr<decltype(value)>(value); // B
};
selfincr(f);
selfincr(i);
std::cout << "f " << f << ", i " << i << std::endl;
return 0;
}
Since line // B
causes a 因为// B
行引起了一个
invalid initialization of non-const reference of type 'T&' from an rvalue of type 'T' 从'T'类型的右值开始无效初始化'T&'类型的非const引用
My immediate guessing has been the removal of the reference, so I added line // A
. 我的直接猜测是删除了引用,所以我添加了行// A
But this yield a 但这会产生一个
no matching function for call to 'incr(T&)' 调用'incr(T&)'没有匹配函数
So how could I remove that reference ? 那我怎么能删除那个引用呢?
So how could I remove that reference ? 那我怎么能删除那个引用呢?
incr<std::remove_reference<decltype(value)>>(value)
, you're specifying std::remove_reference<T>
as the template parameter, but not the type referred by T
(ie decltype(value)
). incr<std::remove_reference<decltype(value)>>(value)
,您指定std::remove_reference<T>
作为模板参数,但不指定T
引用的类型(即decltype(value)
)。 What you want should be 你想要的应该是什么
value = incr<typename std::remove_reference<decltype(value)>::type>(value); // A
// ~~~~~~~~ ~~~~~~
And since C++14 you could make it simpler: 从C ++ 14开始,您可以更简单:
value = incr<std::remove_reference_t<decltype(value)>>(value); // A
// ~~
This: 这个:
value = incr<std::remove_reference<decltype(value)>>(value); // A
doesn't work due to what songyuanyao explained. 由于宋元尧的解释不起作用。
This: 这个:
value = incr<decltype(value)>(value); // B
doesn't work becuase decltype(value)
is a reference type and you're trying to instantiate: 不起作用因为decltype(value)
是一个引用类型,你试图实例化:
float& incr(float& v) { return v + 1; }
int& incr(int& v) { return v + 1; }
You can't bind those expressions to non-const lvalue references, hence the compile error. 您不能将这些表达式绑定到非const左值引用,因此编译错误。
The simplest solution is to just let template deduction do its thing: 最简单的解决方案是让模板推导完成它的事情:
value = incr(value); // C
That will call incr<int>
and incr<float>
as desired. 这将根据需要调用incr<int>
和incr<float>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.