如何将类中的静态const结构用作实数const - 即数组大小

时间:2012-10-18 12:10:28

标签: c++ struct initialization const member

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

有一个结构定义了一些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];

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

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

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

float a[A::c.a];

答案 1 :(得分:1)

我找到的解决方案是使用const成员将struct更改为template 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)