PiotrNycz
PiotrNycz

Reputation: 24430

How to use static const struct from a class as a real const - i.e. an array size

I was asked to provide solution for the following problems:

There is a structure defining some int parameters:

struct B {
  int a;
  int b;
};

One wanted to define this structure as const static members in other classes (not only for this class A - there are other classes expected to have the same set of constants) .

And one wanted to use them as real integral constants:

// .h file
class A {
public:
  static const B c; // cannot initialize here - this is not integral constant
};
// .cpp file
const B A::c = {1,2};

But cannot use this constant to make for example an array:

float a[A::c.a];

Any advice?

Upvotes: 1

Views: 1046

Answers (2)

ecatmur
ecatmur

Reputation: 157484

If you make A::c constexpr you can initialise it inline and use its members as a constant:

struct A {
    static constexpr B c = {1, 2};
};

float a[A::c.a];

Upvotes: 2

PiotrNycz
PiotrNycz

Reputation: 24430

The solution I find, is to change the struct to template struct with const members.

template <int AV, int BV>
struct B {
  static const int a = AV;
  static const int b = BV;
};
template <int AV, int BV>
const int B<AV,BV>::a;
template <int AV, int BV>
const int B<AV,BV>::b;

And usage:

// .h file
class A {
public:
  typedef B<1,2> c; 
};

And an array:

float a[A::c::a]; 
//          ^^ - previously was . (dot)

Upvotes: 1

Related Questions