如何测试表达式是否是临时的? [英] How to test whether expression is a temporary?
问题描述
使用以下宏:
#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
pre>
#define IS_XVALUE(...)std :: is_rvalue_reference< decltype __VA_ARGS __))> :: value
#define IS_PRVALUE(...)!std :: is_reference< decltype((__ VA_ARGS __))> :: value
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, givenstd::string s;
, thenmove(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")
orint()
kind of things, but not themove(s)
and also (for sure) not thes
kind of things. Thedecltype
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 thes
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屋!