如何将static const struct从类中使用作为真实的const-即阵列大小

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

本文关键字:真实 const- 阵列 static const struct      更新时间:2023-10-16

我被要求为以下问题提供解决方案:

有一个定义一些int参数的结构:

struct B {
  int a;
  int b;
};

一个人想将此结构定义为其他类中的const静态成员(不仅对于此class A-预计还有其他类具有相同的常数)

一个人想将它们用作真正的积分常数:

// .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};

,但不能使用此常数使一个数组:

float a[A::c.a];

有任何建议?

如果您制作A::c constexpr,则可以在内联初始化并将其成员用作常数:

struct A {
    static constexpr B c = {1, 2};
};
float a[A::c.a];

我发现的解决方案是用const成员更改structtemplate struct

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;

和用法:

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

和一个数组:

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