jeudi 27 juin 2019

Why can't I use the result of a static constexpr in the declaration of another function in a class?

This is my barebones code:

#include <iostream>
#include <array>

class cColor {
  public:
  enum eValue { k_Red, k_Green, k_Blue };
  static constexpr std::size_t NumValues() { return 3; }
  static constexpr std::array<eValue, NumValues()> Values()  { return {k_Red, k_Green, k_Blue}; }
};

int main() {
  std::cout << "NumColors=" << cColor::NumValues() << '\n';
}

I'm trying to declare Values() as a static constexpr and I thought I should be able to use NumValues() as it's a static constexpr as well. However, this program fails to compile and throws this error:

main.cpp:8:39: error: non-type template argument is not a constant expression
  static constexpr std::array<eValue, NumValues()> Values()  { return {k_Red, k_Green, k_Blue}; }
                                      ^~~~~~~~~~~
main.cpp:8:39: note: undefined function 'NumValues' cannot be used in a constant expression
main.cpp:7:32: note: declared here
  static constexpr std::size_t NumValues() { return 3; }

What am I missing about constexpr here?

Aucun commentaire:

Enregistrer un commentaire