Reference Parameters in Constexpr Functions and Constant Expressions
In C , a constant expression is an expression that evaluates to a constant value at compile-time. Consider the following constexpr function:
template <size_t S1, size_t S2> auto concatenate(const std::array<uint8_t, S1> &data1, const std::array<uint8_t, S2> &data2) { std::array<uint8_t, data1.size() + data2.size()> result; // Possible error here return result; }
When compiling this function using Clang 6.0 with -std=c 17, it fails to compile due to the data1.size() expression being evaluated at runtime. This error occurs only when the parameters are references, indicating a potential misunderstanding about the behavior of reference parameters in constexpr functions.
According to the C standard ([expr.const]/4), an expression is a core constant expression if its evaluation does not involve evaluating an id-expression referring to a variable or data member of reference type unless it has a preceding initialization that is either usable in constant expressions or its lifetime began within the evaluation of the core constant expression.
In the given function, the reference parameters do not have a preceding initialization, rendering their size() expressions non-constant. Therefore, they cannot be used in a constant expression, leading to the compilation error.
To resolve the issue and use the reference parameters in a constant expression, you can simply provide a preceding initialization or replace data1.size() with the template parameter S1.
The above is the detailed content of Can Reference Parameters Be Used in C Constexpr Functions for Constant Expressions?. For more information, please follow other related articles on the PHP Chinese website!