我有一个模板,它依赖于 header 中的常量。像这样:
定义常量的头文件:
// header1.hpp const int CONST_VALUE1 = 10;
我有模板的页眉:
// header2.hpp extern const int CONST_VALUE2; template< int N > struct A { }; struct B { // some member functions A< CONST_VALUE2 > a; };
B的定义和常量的来源
// source2.hpp #include "header2.hpp" // implementation of B const int CONST_VALUE2 = CONST_VALUE1;
这当然不行。错误是这样的:
error: the value of 'CONST_VALUE2' is not usable in a constant expression
note: 'CONST_VALUE2' was not initialized with a constant expression
note: in template argument for type 'int'
有解决办法吗?还是我必须将 header1.hpp 包含到 header2.hpp 中?
最佳答案
模板需要非类型参数的常量表达式。为了
在常量表达式中使用的 const
变量,它的
初始化必须对编译器可见。所以你可能会有
在 header2.hpp 中包含 header1.hpp。
关于c++ - 如何声明在模板中使用的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9393025/