我可以在if语句中初始化不同类型的对象吗?

发布于 2025-01-25 03:12:17 字数 717 浏览 0 评论 0 原文

我知道我可以写作

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

而且,如果不可能的话,是否有任何确切的原因(因此语言律师)?

I know I can write

if (int a = 1; /* whatever */) {}

and even

if (int a = 1, b{3}; /* whatever */) {}

but how can I declare, say, a of type int and b of type std::string?

Such a thing doesn't work:

if (auto a = 1, b{"ciaos"s}; /* whatever */) {}

I've not included a standard, because I'm interested in the answer in general, even though realistically I'd make use of the answer in the context of .

And, if such a thing is not possible, is there any precise reason why (hence )?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拥抱没勇气 2025-02-01 03:12:17

您只允许您在if语句中的一个变量声明语句,每个变量声明语句只能声明单一类型。这是在

if constexpr(opt) ( init-statement condition ) statement

<代码> init-statement 可以是 simple-declaration ,其中包含 init-declarator-list 仅允许单个 声明师 。通常,这仅意味着一种类型,但是指针(*)和参考(&amp;)被应用于变量名称,而不是类型名称,因此您可以拥有 t t*和/或 t&amp; 在单个 init-declarator-list ie中声明的变量, int a = 42, *b =&amp; a,&amp; a,&amp; ; c = a;

作为解决方法,您可以利用结构化绑定 ctad (与 std :: tuple 获得语法,例如

int main()
{
    using namespace std::string_literals;
    if (auto [a, b] = std::tuple{42, "string"s}; a)
    {
        std::cout << b;
    }
}

输出哪些输出

string

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

if constexpr(opt) ( init-statement condition ) statement

and init-statement can be a simple-declaration and that contains a init-declarator-list which only allows a single declarator. Normally this means just a single type, but pointers (*) and references (&) get applied to the variable name, not the type name so you can have T, T*, and/or T& variables declared in a single init-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 like

int main()
{
    using namespace std::string_literals;
    if (auto [a, b] = std::tuple{42, "string"s}; a)
    {
        std::cout << b;
    }
}

which outputs

string
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文