可以constexpr函数返回类型是一个非const? [英] can constexpr function return type be a non const?

查看:235
本文介绍了可以constexpr函数返回类型是一个非const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读过 constexpr 函数返回类型可以是一个非常量,在我的书中也有这样的代码:

I have read that constexpr function return type can be a non const and also in my book there is a code like this:

constexpr bool isShorter(const string& str1, const string& str2)
{
    return str1.size() < str2.size();
}

但是在 str1.size )表示: constexpr 函数返回是非常量。根据书,它必须是正确的,但编译器不同意。

but there is an error under str1.size() that says: constexprfunction return is non-const. According to the book it must be right but the compiler disagree.

每次在不同的代码中使用 constexpr 总是存在此错误:缺少类型说明符 - int。注意:C ++不支持default-int 。但是我不知道这是什么意思。

Also every time I use constexpr in different codes there is always this error: missing type specifier - int assumed. Note: C++ does not support default-int. But I don't know what it means.

推荐答案

不,返回值必须是至少一个的可能输入。

No, the return value must be a constant expression for at least one set of possible inputs.

N3797§7.1.5[dcl.constexpr] / 5说:

N3797 §7.1.5 [dcl.constexpr]/5 says:


对于非模板,非默认的constexpr函数或
非模板,非默认,非继承的constexpr构造函数,如果
没有参数值,则调用函数或
构造函数可以是核心常量
表达式(5.19)的求值子表达式,程序是不成形的;无需诊断。

For a non-template, non-defaulted constexpr function or a non-template, non-defaulted, non-inheriting constexpr constructor, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression (5.19), the program is ill-formed; no diagnostic required.

由于 std :: string :: size constexpr ,不存在返回值是常量表达式的可能情况。

Since std::string::size is not constexpr, there is no possible case where the return value is a constant expression.

这篇关于可以constexpr函数返回类型是一个非const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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