如何测试表达式是否是临时的?
使用以下宏:
#define ASSERT_IF_TEMP(expr) static_assert(?, "Is temporary!");
我应该为问号添加什么?
With the following macro:
#define ASSERT_IF_TEMP(expr) static_assert(?, "Is temporary!");
What should I put for question mark?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先我们要澄清:“暂时”是什么意思?
当很多人说暂时的时候,他们的意思是不同的。从技术上讲,
int()
不是临时的,但大多数人会将它们包含在自己对该术语的含义中。从技术上讲,给定std::string s;
,那么move(s)
也不是临时的,但您可能希望将其与宏视为一个。我上面提到的第一种“临时变量”实际上是“纯右值表达式”。这些是
std::string("foo")
或int()
之类的东西,但不是move(s)
并且(当然)不是s
之类的东西。 decltype 运算符为我上面谈到的第一种“临时变量”生成非引用类型。对于第二种,move(s)
,即 xvalues,它将产生一个右值引用。对于“非临时对象”,即s
情况,它将产生一个左值引用。总而言之,我将定义三个精确的宏,您可以从中选择
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
编辑
我意识到我的方法与您所说的代码执行的操作完全相同,只是逻辑上颠倒了:
您能否详细说明在何种情况下它会违背您的预期?
您可以像这样利用引用折叠规则:
如果
expr
是某种(可能是 const)类型T
的左值,则decltype((expr)) 将解析为
T&
,并且T& &&
将折叠回T&
。否则,如果
expr
是某种类型T
的 xvalue,则decltype((expr))
将是T&&
代码>和<代码>T&& && 将减少为T&&
。否则,
expr
将是某种类型T
的纯右值,decltype((expr))
将产生T
,因此整个类型将是T&&
。示例:
EDIT
I realized that my approach does exactly the same thing as the code you said did not work, only logically inverted:
Could you elaborate as to exactly in what kind of a situation it works against your expectations?
You can exploit the reference-collapsing rules like this:
If
expr
is an lvalue of some (possibly const) typeT
,decltype((expr))
will resolve toT&
, andT& &&
will collapse back toT&
.Otherwise, if
expr
is an xvalue of some typeT
,decltype((expr))
will beT&&
, andT&& &&
will reduce to justT&&
.Otherwise,
expr
will be a prvalue of some typeT
,decltype((expr))
will yieldT
, and thus the whole type will beT&&
.Examples: