如何在C ++中以编程方式确定表达式是右值还是左值? [英] How to determine programmatically if an expression is rvalue or lvalue in C++?

查看:85
本文介绍了如何在C ++中以编程方式确定表达式是右值还是左值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定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

请注意, Yakk的答案将返回不同的类型,这样可以提供更大的灵活性,您应该阅读该答案,并且可能改用它。

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 ++中以编程方式确定表达式是右值还是左值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆