不使用此的constexpr成员函数? [英] constexpr member functions that don't use this?

查看:60
本文介绍了不使用此的constexpr成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下两个C ++ 14程序:

Please consider the following two C++14 programs:

程序1:

struct S { constexpr int f() const { return 42; } };
S s;
int main() { constexpr int x = s.f(); return x; }

程序2:

struct S { constexpr int f() const { return 42; } };
int g(S s) { constexpr int x = s.f(); return x; }
int main() { S s; return g(s); }

这两个程序中的一个或两个都没有错误吗?

Are neither, either or both of these programs ill-formed?

为什么/为什么不呢?

推荐答案

两个程序的格式都正确. C ++ 14标准要求s.f()是常量表达式,因为它被用于初始化constexpr变量,实际上,它是核心常量表达式,因为没有理由不这样做.表达式可能不是核心常量表达式的原因在第5.19 p2节中列出.特别是,它指出表达式的 evaluation 必须执行以下几项操作之一,而您的示例中未完成任何操作.

Both programs are well-formed. The C++14 standard requires that s.f() be a constant expression because it is being used to initialize a constexpr variable, and in fact it is a core constant expression because there's no reason for it not to be. The reasons that an expression might not be a core constant expression are listed in section 5.19 p2. In particular, it states that the evaluation of the expression would have to do one of several things, none of which are done in your examples.

这可能令人惊讶,因为在某些情况下,即使不使用该参数,将非常数表达式传递给constexpr函数也可能导致结果为非常数表达式.例如:

This may be surprising since, in some contexts, passing a non-constant expression to a constexpr function can cause the result to be a non-constant expression even if the argument isn't used. For example:

constexpr int f(int) { return 42; }

int main()
{
    int x = 5;
    constexpr auto y = f(x); // ill-formed
}

但是,其格式不正确的原因是由于非常量表达式的左值到右值转换,这是表达式的 evaluation 不能满足的条件之一允许这样做.在调用s.f()的情况下,不会发生左值到右值的转换.

However, the reason this is ill-formed is because of the lvalue-to-rvalue conversion of a non-constant expression, which is one of the things that the evaluation of the expression is not allowed to do. An lvalue-to-rvalue conversion doesn't occur in the case of calling s.f().

这篇关于不使用此的constexpr成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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