我可以在if语句中初始化不同类型的对象吗?
我知道我可以写作
if (int a = 1; /* whatever */) {}
,但
if (int a = 1, b{3}; /* whatever */) {}
如何声明 int 和 b
b type 字符串?
这样的事情不起作用:
if (auto a = 1, b{"ciaos"s}; /* whatever */) {}
我没有包括标准,因为我对答案一般都感兴趣,即使实际上我会在 c ++ 17 。
而且,如果不可能的话,是否有任何确切的原因(因此语言律师)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只允许您在if语句中的一个变量声明语句,每个变量声明语句只能声明单一类型。这是在
<代码> init-statement 可以是
simple-declaration
,其中包含init-declarator-list
仅允许单个声明师
。通常,这仅意味着一种类型,但是指针(*)和参考(&amp;)被应用于变量名称,而不是类型名称,因此您可以拥有t
,t*和/或
int a = 42, *b =&amp; a,&amp; a,&amp; ; c = a;t&amp;
在单个init-declarator-list
ie中声明的变量,作为解决方法,您可以利用结构化绑定和 ctad (与
std :: tuple
获得语法,例如输出哪些输出
You are only allowed one variable declaration statement in a if statement and each variable declaration statement can only declare a single type. This is convered in [stmt.if]/3 where is shows the grammar for the if statement you are trying to use is
and
init-statement
can be asimple-declaration
and that contains ainit-declarator-list
which only allows a singledeclarator
. Normally this means just a single type, but pointers (*) and references (&) get applied to the variable name, not the type name so you can haveT
,T*
, and/orT&
variables declared in a singleinit-declarator-list
i.e.,int a = 42, *b = &a, &c = a;
As a workaround, you can leverage structured bindings and CTAD (to reduce verbosity) in conjunction with
std::tuple
to get a syntax likewhich outputs