Referencing Non-Constant Parameters in Constexpr Functions
Consider the following function template:
template <size_t S1, size_t S2> auto concatenate(const std::array<uint8_t, S1>& data1, const std::array<uint8_t, S2>& data2) { // Error in constexpr contexts due to reference parameter std::array<uint8_t, data1.size() + data2.size()> result; // ... }
Using Clang 6.0 with C 17, this code fails to compile with the error "non-type template argument is not a constant expression." Evaluating references within constexpr functions is problematic due to potential aliasing issues.
Understanding the Standard
According to the C Standard ([expr.const]/4), an expression cannot be a core constant expression if it evaluates to a reference that:
Solution
To resolve this issue, one can substitute the problematic reference parameter with its corresponding template parameter:
template <size_t S1, size_t S2> auto concatenate(const std::array<uint8_t, S1>& data1, const std::array<uint8_t, S2>& data2) { // Problem solved by using S1 + S2 instead std::array<uint8_t, S1 + S2> result; // ... }
By using the template parameters directly, we eliminate the need for evaluating references in constexpr contexts and ensure that the function can be used in constant expression evaluations.
The above is the detailed content of How Can I Resolve \'Non-type Template Argument is Not a Constant Expression\' Errors in Constexpr Functions with References?. For more information, please follow other related articles on the PHP Chinese website!