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

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

 



---------- Forwarded message ---------
From: Yu Sheng Oh <humbleoh@xxxxxxxxx>
Date: Fri, Dec 20, 2024 at 2:30 AM
Subject: Re: constant expression context for `std::string_view`
To: Hans Åberg <haberg_1@xxxxxxxxxx>


referring to my previous code, line 16 is a constant expression. if
`static_assert` at line 8 is removed, then the compilation would
succeed. if `string_view` object is created at runtime, the compiler
should complain about line 16 when line 8 is removed. giving another
simple test code in the following, which passes the compilation, if
line 14 is uncommented, the compilation will fail again. i just doubt
if it is a bug in the compiler or i have missed something about the
constant expression. 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)
  7 {
  8   static_assert(s.size() > N);
  9   return { 0 };
 10 }
 11
 12 constexpr std::string_view test2(std::string_view s)
 13 {
 14   //static_assert(s.size() > 0);
 15   return s;
 16 }
 17
 18 int main(int argc, char *argv[])
 19 {
 20   using namespace std::literals;
 21   constexpr auto s = "123"sv;
 22   //constexpr auto a = test<2>(s);
 23   constexpr auto s2 = test2(s);
 24   return 0;
 25 }

On Fri, Dec 20, 2024 at 1:38 AM Hans Åberg <haberg_1@xxxxxxxxxx> wrote:
>
> The string_view object is created at runtime, for example this code passes:
> #include <stdlib.h>
> #include <iostream>
> #include <string_view>
> #include <vector>
>
> int main(int argc, char* argv[], char* envp[]) {
>   std::vector<std::string_view> args(argv, argv + argc);
>
>   for (auto& i: args)
>     std::cout << i << std::endl;
>
>   return EXIT_SUCCESS;
> }
>
>
> > On 19 Dec 2024, at 15:34, 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)
> >  7 {
> >  8   static_assert(s.size() > N);
> >  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 }
>
>




[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