1

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

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

有什么建议吗?

4

2 回答 2

2

如果你这样做A::c constexpr,你可以内联初始化它并将其成员用作常量:

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

float a[A::c.a];
于 2012-10-18T12:16:04.007 回答
1

我找到的解决方案是使用 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)
于 2012-10-18T12:10:28.027 回答