0

I just finished upgrading my compiler to C++20 on ubuntu 20.04. g++ version gives me the following output :

c++ (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0

I am trying the following code as suggested on stackoverflow

constexpr int f() {
    std::vector<int> v = {1, 2, 3};
    return v.size();
}

int main() {
    static_assert(f() == 3);
}

But I am getting the following error :

error: variable ‘v’ of non-literal type ‘std::vector<int>’ in ‘constexpr’ function

Am I going wrong somewhere. Or is my installation incorrect

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
user3282758
  • 1,379
  • 11
  • 29
  • You probably didn't enable 20 standard support. Put -std=c++20 to your compiler options list – George Sep 18 '22 at 07:20
  • I am already compiling using `-std=c++20`. The problem is still there. Some other features like `cobsteval` and `constinit` are working fine though – user3282758 Sep 18 '22 at 07:30
  • I've tried your code in [godbolt](https://godbolt.org/) with gcc compiler, it produces the same error up to version 11.3 (including 10.3), but works fine starting from 12.1 – George Sep 18 '22 at 07:44
  • I don't know how you upgraded your compiler, but it's not close to the latest version. C++20 is not yet fully implemented by all compilers, even in the latest version. That a compiler has a C++20 flag doesn't guarantee that. Only MSVC say they have every C++20 feature, but that doesn't guarantee you can't run into a bug . – JHBonarius Sep 18 '22 at 07:55
  • I found that ubuntu 20.04 does not support gcc 12.1 and hence not all features are supported – user3282758 Sep 18 '22 at 07:58
  • @user3282758 that's nonsense. You can always [install from source](https://tutorialforlinux.com/2022/05/25/step-by-step-gcc-12-1-ubuntu-20-04-installation-guide/) – JHBonarius Sep 18 '22 at 08:00
  • Of course building from source would work. The update gave me what I mentioned earlier. Not everyone is as informed as you might be. Some may need support and time – user3282758 Sep 18 '22 at 08:15
  • Dupe: [both `constexpr std::vector` and `constexpr std::basic_string` are now implemented in gcc 12](https://stackoverflow.com/a/52801072/12002570) – Jason Sep 18 '22 at 13:30
  • Don't take my comments as intended shaming or such. I think there is a clash of cultures here. I'm just trying to inform you. – JHBonarius Sep 18 '22 at 14:01

1 Answers1

6

You need to upgrade gcc to at least 12 to get the C++23 constexpr support for non-literal types as std::vector<int>.

From compiler support @ cppreference:

gcc clang EDG eccp
Non-literal variables (and labels and gotos) in constexpr functions P2242R3 12 15 6.3

Feature test:

__cpp_constexpr >= 202110L
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Dupe: [both `constexpr std::vector` and `constexpr std::basic_string` are now implemented in gcc 12](https://stackoverflow.com/a/52801072/12002570) – Jason Sep 18 '22 at 13:31