【问题标题】:How to use static const struct from a class as a real const - i.e. an array size如何将类中的静态 const 结构用作真正的 const - 即数组大小
【发布时间】:2012-10-08 21:22:23
【问题描述】:

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

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

有什么建议吗?

【问题讨论】:

    标签: c++ struct initialization constants member


    【解决方案1】:

    我找到的解决方案是将 struct 更改为 template struct 与 const 成员。

    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)
    

    【讨论】:

    • 为什么你没有在你的答案中发布它?
    • @DenisErmolin 他应该在哪里发布解决方案?
    • 使用enum {a = AV, b = BV},常用的IntToType成语可以简化一点
    • @YanZhou 是的,但真正的问题是在不同的类中拥有完全相同的一组常量——不仅是class A...
    【解决方案2】:

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

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

    【讨论】:

    • 我不能使用它——“对 constexpr 的支持是在 4.6 中首次添加到 GCC 中的”——我们有更早的版本。但是对于更新的编译器,您的解决方案比我的 (+1) 更好。
    猜你喜欢
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多