如何测试表达式是否是临时的? [英] How to test whether expression is a temporary?

查看:220
本文介绍了如何测试表达式是否是临时的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下宏:

  #define ASSERT_IF_TEMP(expr)static_assert 

我应该为问号放什么?

解决方案

首先我们应该澄清一下:临时是什么意思?



。从技术上讲, int()不是一个临时的,但大多数人会将它们包含在自己对该术语的意义上。技术上,给定 std :: string s; ,然后 move(s)可能想把它作为一个与你的宏。



我上面提到的第一种临时是真正的prvalue表达式。这些是 std :: string(foo) int() code> move(s)以及(当然)不是 s decltype 运算符产生了上面讨论的第一种临时的非引用类型。对于第二种类型, move(s),它们是xvalue,它将产生一个右值引用。对于非临时性,即 s 情况,它将产生一个左值引用。



总而言之,我将定义三个精确的宏,您可以从中选择

  #define IS_LVALUE(...)std :: is_lvalue_reference< decltype((__ VA_ARGS __))> :: value 
#define IS_XVALUE(...)std :: is_rvalue_reference< decltype __VA_ARGS __))> :: value
#define IS_PRVALUE(...)!std :: is_reference< decltype((__ VA_ARGS __))> :: value
pre>

With the following macro:

#define ASSERT_IF_TEMP(expr) static_assert(?, "Is temporary!");

What should I put for question mark?

解决方案

First we should clarify: What do you mean by "temporary"?

Many people mean different things when they say temporary. Technically, int() is not a temporary, but most people will include them into their own meaning of that term. Technically, given std::string s;, then move(s) isn't a temporary either, but you may want to treat it as one with your macro.

The first kind of "temporaries" I mentioned above are really "prvalue expressions". Those are the std::string("foo") or int() kind of things, but not the move(s) and also (for sure) not the s kind of things. The decltype operator yields a non-reference type for the first kind of "temporaries" I talked about above. For the second kind, move(s), which are xvalues, it will yield an rvalue reference. And for the "non-temporaries", i.e the s cases, it will yield an lvalue reference.

So to summarize, I will define three precise macros, and you can choose from them

#define IS_LVALUE(...) std::is_lvalue_reference<decltype((__VA_ARGS__))>::value
#define IS_XVALUE(...) std::is_rvalue_reference<decltype((__VA_ARGS__))>::value
#define IS_PRVALUE(...) !std::is_reference<decltype((__VA_ARGS__))>::value

这篇关于如何测试表达式是否是临时的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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