Home > Backend Development > C++ > Why Doesn\'t `data1.size()` Work in a `constexpr` Function with Reference Parameters?

Why Doesn\'t `data1.size()` Work in a `constexpr` Function with Reference Parameters?

Patricia Arquette
Release: 2024-11-29 07:53:13
Original
645 people have browsed it

Why Doesn't `data1.size()` Work in a `constexpr` Function with Reference Parameters?

Constant Expressions in Constexpr Functions with Reference Parameters

Consider the following code snippet:

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: non-type template argument is not a constant expression
    ...
}
Copy after login

When compiled using clang 6.0 with -std=c 17, the function fails to compile due to the size member function of the array not being constexpr when applied to a reference.

Standard Rationale

The reason for this behavior is explained in [expr.const]/4 of the C standard:

  • An expression is not a core constant expression if it evaluates an id-expression that refers to a variable or data member of reference type unless:

    • The reference has a preceding initialization and is usable in constant expressions
    • The lifetime of the reference began within the evaluation of the expression

In this case, the reference parameter data1 does not have a preceding initialization, so it cannot be used in the constant expression data1.size() data2.size().

Solution

To resolve the issue, simply replace data1.size() with the template parameter S1:

std::array<uint8_t, S1 + S2> result;
Copy after login

The above is the detailed content of Why Doesn\'t `data1.size()` Work in a `constexpr` Function with Reference Parameters?. 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