Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static const vs constexpr member fields in C++11/14?

What is the difference between these member variables:

struct my_class {
    static const int i = 0;
    static constexpr int j = 0;
};

If my understanding is correct, I'm able to use both i and j as compile time constants. That is, both std::array<int, my_class::i> and std::array<int,my_class::j> should work.

like image 777
amin Avatar asked Mar 29 '16 10:03

amin


1 Answers

There is no difference for members of integral or enumeration type (as in your example). For all other types, constant expressions require constexpr:

an lvalue-to-rvalue conversion (4.1) unless it is applied to

  • a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression, or […]
  • a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable sub-object of such an object, or […]
like image 114
Columbo Avatar answered Oct 05 '22 19:10

Columbo