Use of constexpr function before definition fails

后端 未结 2 604
[愿得一人]
[愿得一人] 2020-12-16 10:53

I\'m having some trouble with constexpr. The book C++ Primer shows a line of code:

  constexpr int sz = size(); // only size() is a con         


        
相关标签:
2条回答
  • 2020-12-16 11:19

    A constant expression function must be defined before its first use. See this paper, end of section 4.1.

    0 讨论(0)
  • 2020-12-16 11:20

    A constexpr function does NOT have to be defined before its first use, however the result of any call made prior to definition is not a constant expression.

    Source: C++ Standard draft n4296, section 5.20:

    A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

    • this, except in a constexpr function or a constexpr constructor that is being evaluated as part of e;
    • an invocation of a function other than a constexpr constructor for a literal class, a constexpr function, or an implicit invocation of a trivial destructor [ Note: Overload resolution is applied as usual — end note ];
    • an invocation of an undefined constexpr function or an undefined constexpr constructor;
    • ...

    version from draft 3485 (section 5.19):

    A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression, but subexpressions of logical AND, logical OR, and conditional operations that are not evaluated are not considered [ Note: An overloaded operator invokes a function. — end note ]:

    • this [ Note: when evaluating a constant expression, function invocation substitution replaces each occurrence of this in a constexpr member function with a pointer to the class object. — end note ];
    • an invocation of a function other than a constexpr constructor for a literal class or a constexpr function [ Note: Overload resolution is applied as usual — end note ];
    • an invocation of an undefined constexpr function or an undefined constexpr constructor
    • ...

    The example int x2 = s. t(); in n2235 actually became valid due to the changes made prior to Standardization. However, constexpr int x2 = s. t(); remains an error.

    0 讨论(0)
提交回复
热议问题