• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

c++ - 延迟局部变量初始化的constexpr函数

[复制链接]
菜鸟教程小白 发表于 2022-8-3 00:55:43 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在尝试编写以下形式的constexpr函数:

constexpr int foo(bool cond) {
    int a, b, c;
    if (cond) {
        a = 1;
        b = 2;
        c = 3;
    }
    else {
        a = -1;
        b = -2;
        c = -3;
    }

    return a + b + c;
}

但是,编译器提示我正在使用未初始化的变量,尽管事实上可以保证局部变量的最终初始化。

我可以重写该函数以使用三元运算符,即int a = cond ? 1 : -1;等,但我不希望这样做。有没有办法说服编译器局部变量将被初始化?



Best Answer-推荐答案


However, the compiler complains that I am using an uninitialized variables, despite the fact that the eventual initialization of the local variables is guaranteed.



初始化或不初始化,没有“最终初始化”。并且,对于constexpr函数,在[dcl.constexpr]中有一个要求:

The definition of a constexpr function shall satisfy the following requirements: [...] its function-body shall be = delete, = default, or a compound-statement that does not contain [...] a definition of a variable of non-literal type or of static or thread storage duration or for which no initialization is performed.


constexpr函数中不能包含未初始化的变量,abc适合您。

所以,你可以做什么?您可以将abc初始化为零。这就绕过了这个要求。或者,您可以在a的每个范围内初始化bcif。或者,您可以使用另一个constexpr函数进行求和:
constexpr int f(int a, int b, int c) { return a+b+c; };

constexpr int foo(bool cond) {    
    if (cond) {
        return f(1,2,3);
    }
    else {
        return f(-1,-2,-3);
    }    
}

有很多解决方法。

关于c++ - 延迟局部变量初始化的constexpr函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509106/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap