I would like to get the number of elements in the array of non-static members of the class as a constant expression within the non-static member function, but using the std::size
function results in a compilation error.
Is it not appropriate to use the std::size
function in this situation?
sizeof(buffer)/sizeof(buffer[0])
can be obtained by a constant expression, but I would like to avoid it if possible.
code:
#include<stdio.h>
# include <iterator>
US>structure S{
int buffer [2048];
void foo() {
constexpr size_tN=std::size(buffer);
// constexpr size_t N=sizeof(buffer)/sizeof(buffer[0]);
// Processing with N...
printf("%zu\n",N);
}
};
int main (void)
{
Ss;
s.foo();
}
Results on clang15:
$clang++prog.cc-Wall-Wextra-pedantic-std=c++20-lm
prog.cc:8:26:error:constexpr variable'N'must be initialized by a constant expression
constexpr size_tN=std::size(buffer);
^ ~~~~~~~~~~~~~~~~~
prog.cc:8:40:note:implicit use of 'this' pointer is only allowed with the evaluation of a call to a'constexpr' member function
constexpr size_tN=std::size(buffer);
^
1 error generated.
std::size
function does not result in compilation errors unless it is a
This is not a very good answer, but I changed the C array to std::array
and used std::tuple_size_v
(or std::tuple_size
) instead of std::size
.
structure S{
std::array<int,2048>buffer;
void foo() {
constexpr size_tN=std::tuple_size_v<decltype(buffer)>
// Processing with N...
printf("%zu\n",N);
}
};
© 2024 OneMinuteCode. All rights reserved.