2

The following code fails on g++ (tried 10.3, 11.2 and trunk on Compiler Explorer) and clang (tried trunk) but compiles (and seems to run fine) on MSVC. It's a contrived example meant to narrow down an issue I am seeing on a bigger code base.

Is that a case of g++/clang lagging behind MSVC in terms of constexpr support? If not, what's not legal in that snippet?

#include <utility>

struct Foo {
  template<std::size_t ...NN>
  static constexpr int sum_sequence(std::index_sequence<NN...>) {     
    return (NN + ...);    
  }
  inline static constexpr int sum =
      sum_sequence(std::make_index_sequence<10>()); // 10 could be any non negative integer
};

Error seen on g++ (-std=c++20):

<source>:9:19: error: 'static constexpr int Foo::sum_sequence(std::index_sequence<NN ...>) [with long unsigned int ...NN = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::index_sequence<NN ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9>]' used before its definition
    9 |       sum_sequence(std::make_index_sequence<10>());
      |       ~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Error seen on clang (-std=c++20):

<source>:8:31: error: constexpr variable 'sum' must be initialized by a constant expression
  inline static constexpr int sum =
                              ^
<source>:9:7: note: undefined function 'sum_sequence<0, 1, 2, 3, 4, 5, 6, 7, 8, 9>' cannot be used in a constant expression
      sum_sequence(std::make_index_sequence<10>());
      ^
<source>:5:24: note: declared here
  static constexpr int sum_sequence(std::index_sequence<NN...>) {     
gg99
  • 445
  • 6
  • 12
  • Might be that MSVC is being overly permissive, going from [this question](https://stackoverflow.com/questions/36378194/why-is-expanding-a-parameter-pack-into-an-array-not-a-constant-expression). – Nathan Pierson Aug 23 '21 at 23:29
  • @Artyer: if that's the case, that would make clang's output the best of all 3 in terms of explicitness - MSVC would then be overly permissive while gcc to me is failing in a cryptic way. What exactly is not constexpr friendly there? The fold expression? The use of std::index_sequence? – gg99 Aug 23 '21 at 23:48
  • Interestingly in the g++ case I found a similar case (in terms of the output message) categorized as a bug, when dealing with constexpr virtual destructors : https://www.mail-archive.com/gcc-bugs@gcc.gnu.org/msg681237.html – gg99 Aug 23 '21 at 23:50

0 Answers0