是否有必要为返回void的函数声明constexpr? [英] Any reason to declare constexpr for a function that returns void?

查看:80
本文介绍了是否有必要为返回void的函数声明constexpr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我读到的内容:对静态成员函数使用别名吗?

在答案中,我看到一个建议使用 constexpr 。为 void 函数使用 constexpr 的原因是什么。

In the answer I see a suggestion to use constexpr. What is the reason to use constexpr for void functions.

请演示一个简单的用例。我是 constexpr 的新手,所以在复杂的示例中,我将不理解要点。

Please demonstrate a simple use case. I am new to constexpr so in complex examples I will not understand the gist.

推荐答案

Rahul的答案引用了标准段落,该段落允许 void constexpr 函数,但它没有。给出一个用例。我想到的一个用例是拥有一个 constexpr 类,并像往常一样在助手方法中排除方法所共有的行为。该标准明确提到了功能检查,例如断言。我手头没有具体的例子,但是我可以想象

Rahul's answer cites the standard paragraph which allow void constexpr functions, but it doesn't give a use-case. One use-case that comes to my mind would be to have a constexpr class, and as usual factor out behavior common to method in helper methods. The standard explicitly mentions function doing checks, e.g. assertions. I don't have a concrete example at hand, but I can imagine something like

class A
{
public:
    constexpr X doSomething(Y arg1) {
        checkInvariant();
        constraintOnYArgument(arg1);
        // ...
        checkInvariant();        
    }

    constexpr X doSomethingElse(Y arg1) {
        checkInvariant();
        constraintOnYArgument(arg1);
        // ...
        checkInvariant();        
    }

private:
    constexpr void constraintOnYArguments(Y arg) {
    }

    constexpr void checkInvariant() {
        // some checks
        if (!some condition) {
            throw std::logic_error("Oh no!");
        }
    }
};

这篇关于是否有必要为返回void的函数声明constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆