Home > Backend Development > C++ > Why Do Reference Parameters Cause Errors in Constexpr Functions?

Why Do Reference Parameters Cause Errors in Constexpr Functions?

Mary-Kate Olsen
Release: 2024-12-15 17:57:15
Original
931 people have browsed it

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

    // ...
}
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template