Static member access in constant expressions

后端 未结 2 2060
一整个雨季
一整个雨季 2020-12-04 01:42

Accessing static class member functions or variables, can be done in two ways: through an object (obj.member_fun() or obj.member_var) or through th

2条回答
  •  爱一瞬间的悲伤
    2020-12-04 02:13

    constexpr auto v = s.v();   // ERROR for clang, OK for gcc
    

    I guess it depends on whether you compile in C++11 or C++14 mode. If you look over at cppreference, you will find (emphasis added by me):

    A core constant expression is any expression that does not have any one of the following
    (...)
    6) The this pointer, except if used for class member access inside a non-static member function (until C++14)
    6) The this pointer, except in a constexpr function or a constexpr constructor that is being evaluated as part of the expression (since C++14)

    So, in C++11, whatever happens inside s.v() would not be considered a constant expression, since it uses the this pointer, but it is not a non-static member function (it's static) accessing a class member.

    Per C++14, however, it would be, since it is evaluating a constexpr function as part of the expression, so the "except if" clause on the "does not have any of" set of rules catches.

    Now don't ask me whether that makes any sense or whether anyone is supposed to understand that... :-)

提交回复
热议问题