问题描述
确定C ++中表达式是右值还是左值的最佳方法是什么?可能这在实践中没有用,但是由于我正在学习rvalues和lvalues,我认为最好有一个 is_lvalue
函数,如果在输入中传递的表达式为一个左值,否则为false。
What's the best way to determine if an expression is a rvalue or lvalue in C++? Probably, this is not useful in practice but since I am learning rvalues and lvalues I thought it would be nice to have a function is_lvalue
which returns true if the expression passed in input is a lvalue and false otherwise.
示例:
std::string a("Hello");
is_lvalue(std::string()); // false
is_lvalue(a); // true
推荐答案
大部分工作已完成您只需使用stdlib,您只需要一个函数包装器即可:
Most of the work is already done for you by the stdlib, you just need a function wrapper:
template <typename T>
constexpr bool is_lvalue(T&&) {
return std::is_lvalue_reference<T>{};
}
如果您传递了 std :: string
左值,然后 T
将推导为 std :: string&
或 const std :: string&
,对于右值,它将推导出为 std :: string
in the case you pass a std::string
lvalue then T
will deduce to std::string&
or const std::string&
, for rvalues it will deduce to std::string
请注意,将返回不同的类型,这样可以提供更大的灵活性,您应该阅读该答案,并且可能改用它。
Note that Yakk's answer will return a different type, which allows for more flexibility and you should read that answer and probably use it instead.
这篇关于如何在C ++中以编程方式确定表达式是右值还是左值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!