c++ - 如何使用类命名空间中的常量作为数组和模板参数?

标签 c++ compiler-errors constants static-members c++98

我想使用类命名空间中的常量作为静态数组的大小和另一个类中的模板参数。我有跟随错误

// MS VS 2010 C++98
// A.h
class A
{
public:
 const static int someNumber;
};
// A.cpp
#include <A.h>
const int  A::someNumber = 5;

// B.h
#include <A.h>
class B
{
  std::bitset<A::someNumber> btst; // Error! C2975: '_Bits' : invalid template argument 

  double control[A::someNumber];   // Error! C2466: cannot allocate an array of constant size 0
};

我怎样才能避免它们?

最佳答案

在 C++98 中,您不能使用 constexpr,因为它直到 C++11 才被引入。

double control[A::someNumber] 需要编译时可评估并且您的定义 A::someNumber 驻留在不同的翻译单元中。这就是您的编译器所提示的。

但是您可以使用枚举。我从模板元编程中使用的习语中借用了这项技术:

class A
{
public:
    enum {someNumber = 5};
}; /*and note this semicolon*/

关于c++ - 如何使用类命名空间中的常量作为数组和模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28151299/

相关文章:

c++ - "Materializing"用于 C++ 类型推断的已知类型的对象

terminal - 通过cygwin终端在我的Windows上安装hydra时“no acceptable c compiler found in $PATH”

compiler-errors - “make all” 编译TPlink wm722n驱动出错

memory - CUDA中常量内存的动态分配

c++ - 引用数据成员更改 const 函数内的另一个数据成员

c++ - vector 作为对象,push_back 错误 - "("标记之前的预期主表达式

c++ - 将对象(而不是指针)向下转换为它们已知的派生类型是否安全?

c++ - qt 绕 x 轴和 y 轴旋转

c++ - c++/g++ —编译错误.. fatal error : iostream: No such file or directory compilation terminated

c++ - 使用 const 指针初始化 const 结构