c++ - Initializing static constexpr variables and classes inside a struct -


here working code example:

#include <iostream>  template<typename b> class b { public:     int y;      constexpr b(int x) : y(x) {      }      constexpr void sayhi() {         std::cout << "hi" << std::endl;     } };    template<int x> struct {     static constexpr b<int> bee = x;     static constexpr int y = x;         // 1 fine , usable already, don't have did on member bee      inline static void sayhi() {         std::cout << y << std::endl;     } };  template<int x> constexpr b<int> a<x>::bee;        // why have this, cause errors if don't.  int main(int argc, char** argv) {     a<30>::bee.sayhi();             // works fine     a<30>::sayhi();                 // works fine      return 0; } 

what code simple, have template struct a has 2 static variables, namely static constexpr int y , static constexpr b<int> bee = x;. template struct a value of argument copied x template parameter. question is: how come when comes classes, have initialize class doing this:

template<int x> constexpr b<int> a<x>::bee;  

if don't use code above, undefined reference error. wherein int fine , accessible doing like:

static constexpr int y = x;     

i concerned why don't have forward declare anymore.

a static constexpr member has value upon initialization inside class { } scope, not have location in memory (an address) until defined outside class { }. reason may decide include or of specializations in link library (e.g. .o or .so), or whether give effectively-inline linkage specializations default.

the out-of-class definition required if address of object ever used, implies must exist global variable. on other hand, if want constexpr member exist @ compile time, prohibiting global storage allocation, omitting definition choice.

by way, it's not allowed put constexpr specifier on function can never evaluated constant expression, such sayhi prints std::cout. "no diagnostic required (ndr)" rule, meaning compiler might not complain next compiler version might.


Comments