I want to get the number of elements in the array of non-static members of the class as a constant expression

Asked 1 years ago, Updated 1 years ago, 432 views

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.
  • gcc12 results in a similar compilation error.
  • The std::size function does not result in compilation errors unless it is a
  • const expression.

c++

2023-01-18 22:17

1 Answers

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);
    }
};


2023-01-19 05:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.