加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C constexpr自动成员功能. Clang问题?

发布时间:2020-12-16 09:57:51 所属栏目:百科 来源:网络整理
导读:#include utility struct A { constexpr auto one(int a) { return std::integral_constantint,_data[a]{}; } constexpr int two(int a) const { return _data[a]; } int _data[10]; }; int main() { constexpr auto ex = A{{1,2,3,4,5,6,7,8,9,10}}; std::i
#include <utility>

 struct A {
     constexpr auto one(int a) {
         return std::integral_constant<int,_data[a]>{};
     }
     constexpr int  two(int a) const {
         return _data[a];
     }

     int _data[10];
 };

 int main() {
     constexpr auto ex = A{{1,2,3,4,5,6,7,8,9,10}};

     std::integral_constant<int,ex.two(3)> b{};
 }

上面的代码不会在trunk Clang中编译.错误发生在one()成员函数中,并说:

cc.cpp:57:44: note: implicit use of 'this' pointer is only allowed 
  within the evaluation of a call to a 'constexpr' member function.

显然,函数被标记为constexpr,如果你注释掉one()成员,一切都编译得很好,所以我们显然能够从ex创建integral_constant,但不能直接从struct创建?看来,当我需要自动返回类型扣除时,它失败并声称功能不是constexpr?

这是预期的吗?我觉得这应该不是问题,如果这是预期的行为,我会感到惊讶.

解决方法

如果你在[dcl.constexpr] / 7中考虑这个陈述:

A call to a constexpr function produces the same result as a call to an equivalent non-constexpr function in all respects except that a call to a constexpr function can appear in a constant expression.

考虑非constexpr等效函数A :: one(). _data [a]不能用在常量表达式中(作为非类型模板参数),因为它将涉及从[expr.const]中对此进行求值:

A conditional-expression e is a core constant expression unless the evaluation of e,following the rules of the
abstract machine (1.9),would evaluate one of the following expressions:
(2.1) — this (5.1.1),except in a constexpr function or a constexpr constructor that is being evaluated as
part of e;

由于非constexpr等价物是不正确的,因此constexpr函数给出相同的结果是合理的.

另一方面,无论constexpr如何,two()都是格式良好的成员函数,并且你对ex.two(3)的使用作为常量表达式是有效的 – 这就是它编译的原因.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读