0

What doe the diagnostic below mean? I do not understand how a call to a correct consteval function with no arguments can possibly be anything other than a constant expression.

#include <iostream>
template<int x>
struct X {
consteval static int get() { return x; }
int f() const { return get(); }
};

int main() {
  ::std::cout << X<4>().get() << ::std::endl;
}
~/felix>clang++ -std=c++20 -ferror-limit=1 xx.cxx
xx.cxx:4:17: error: call to consteval function 'X::get' is not a constant expression
int f() const { return get(); }
                        ^

clang is confused. Here's the proof: this works:

int f() const { int a[get()]; return sizeof(a); }

clang thinks a consteval function can ONLY be used in a context where a constant expression is required: whether or not that is the rule in the Standard it's nonsense. In my actual code, the function is successfully called without a diagnostic if qualified by a template typename parameter, and is used in a context which does not require a constant.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Yttrill
  • 4,725
  • 1
  • 20
  • 29
  • "_Here's the proof: this works:_": By default Clang allows variable-length arrays. So the test doesn't show what you want to show. Try it again with `-pedantic-errors`. – user17732522 Dec 05 '22 at 05:24
  • Seems to be fixed in (upstream) Clang 15. Don't know which Apple Clang version that translates to. See https://godbolt.org/z/qaTj7Przf. – user17732522 Dec 05 '22 at 05:26
  • @-user17732522~/felix>clang++ -std=c++20 -ferror-limit=1 -pedantic-errors xx.cxx ~/felix>./a.out 4 – Yttrill Dec 05 '22 at 05:27
  • @-user17732522 ~/felix>clang++ --version Apple clang version 14.0.0 (clang-1400.0.29.202) Target: x86_64-apple-darwin21.6.0 – Yttrill Dec 05 '22 at 05:28
  • @-user17732522 ok, thanks! .. Apple clang is usually quite a bit behind and at least the library is modified as well. Spaceship <=> doesn't work correctly either in my version (which was updated today lol) – Yttrill Dec 05 '22 at 05:30
  • Ah ok. You are right that it works even with `-pedantic-errors`. According to https://en.wikipedia.org/wiki/Xcode most recent versions of Xcode are using upstream LLVM/Clang 14. So you'll have to wait at least another release to get the bugfix. – user17732522 Dec 05 '22 at 05:33

1 Answers1

2

The program is well-formed and this is a clang bug which has been fixed in clang 15.0.

Demo

Jason
  • 36,170
  • 5
  • 26
  • 60
  • Thanks! Whew! I really need that to be a compile time constant, since in the real code it's using polymorphic recursion over parameter packs, and it has to be not only fast at run time, I'm about to use it in a context where it does have to be a constant expression. – Yttrill Dec 05 '22 at 05:32