Home >Backend Development >C++ >Why Do Reference Parameters Cause Errors in Constexpr Functions?
Confusion over Reference Parameters in Constexpr Functions
The code snippet below attempts to concatenate two arrays of bytes into a new array within a constexpr function named concatenate.
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; // Error occurs here // ... }
However, when compiled with Clang 6.0 using the C 17 standard, an error occurs: "non-type template argument is not a constant expression." This error stems from the reference nature of the function parameters (data1 and data2).
The reference type in the function parameter triggers an issue because constant expressions cannot evaluate references, as stated in the C standard under [expr.const]/4:
"An expression e is a core constant expression unless the evaluation of e... would evaluate an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization."
Since the reference parameters in this case do not have a preceding initialization, they cannot be utilized in a constant expression.
To rectify this issue, the code can be modified to utilize the S1 and S2 template parameters directly instead of relying on the reference parameters' size() member function:
std::array<uint8_t, S1 + S2> result;
The above is the detailed content of Why Do Reference Parameters Cause Errors in Constexpr Functions?. For more information, please follow other related articles on the PHP Chinese website!