Re: constant expression context for `std::string_view`

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, 19 Dec 2024, 14:35 Yu Sheng Oh via Gcc-help, <gcc-help@xxxxxxxxxxx>
wrote:

> Hi guys,
>
> May I know why the compilation failed for the following code where the
> compiler is complaining that `s` is not a constant expression? While
> removing the `static_assert`, the compilation passed. Regards.
>
>   1 #include <array>
>   2 #include <string_view>
>   3 #include <cstddef>
>   4
>   5 template<std::size_t N>
>   6 constexpr std::array<int, N> test(std::string_view s)
>

s is a function parameter, that is never a constant expression. It doesn't
matter that it's a constexpr function, and it even wouldn't matter if it
was consteval.


  7 {
>   8   static_assert(s.size() > N);
>

You cannot use s here because it's not a constant expression.

  9   return { 0 };
>  10 }
>  11
>  12 int main(int argc, char *argv[])
>  13 {
>  14   using namespace std::literals;
>  15   constexpr auto s = "123"sv;
>  16   constexpr auto a = test<2>(s);
>  17   return 0;
>  18 }
>
> The g++ version being used is g++-14 (Homebrew GCC 14.2.0_1) 14.2.0.
>
> Error messages:
> test.cpp: In instantiation of 'constexpr std::array<int, N>
> test(std::string_view) [with long unsigned int N = 2; std::string_view
> = std::basic_string_view<char>]':
> test.cpp:16:29:   required from here
>    16 |   constexpr auto a = test<2>(s);
>       |                      ~~~~~~~^~~
> test.cpp:8:26: error: non-constant condition for static assertion
>     8 |   static_assert(s.size() > N);
>       |                 ~~~~~~~~~^~~
> In file included from test.cpp:2:
> test.cpp:8:23:   in 'constexpr' expansion of
> 's.std::basic_string_view<char>::size()'
> /opt/homebrew/Cellar/gcc/14.2.0_1/include/c++/14/string_view:230:22:
> error: 's' is not a constant expression
>   230 |       { return this->_M_len; }
>       |                ~~~~~~^~~~~~
>



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux