c++ - 如何声明在模板中使用的常量?

标签 c++ templates c++11

我有一个模板,它依赖于 header 中的常量。像这样:

  1. 定义常量的头文件:

    // header1.hpp
    const int CONST_VALUE1 = 10;
    
  2. 我有模板的页眉:

    // header2.hpp
    extern const int CONST_VALUE2;
    
    template< int N >
    struct A
    {
    };
    struct B
    {
      // some member functions
      A< CONST_VALUE2 > a;
    };
    
  3. 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/

相关文章:

c++ - 有人可以解释一下这段代码中使用 BaseTypeX::BaseTypeX 吗?

c++ - 将抽象重写方法传递给 Boost::Thread

c++ - 信号/槽概念 Qt 和模板...替代方案?

c++ - 在多核 MacOSX 上,以下 c++ 代码是线程安全的吗?

c++ - std::mutex 顺序一致吗?

c++ - 消除可变类层次结构中无参数函数调用的歧义

c++ - 使用模板化基类型对派生结构进行结构初始化

c++ - 定义类

html - 直接在 float 图像后添加内容

java - jsf页面中的空白页面