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 ... }
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:
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;
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!