c++ - 如何在不同文件中使用 C++ extern 常量作为模板参数

标签 c++ templates extern bitset

我有以下 5 个文件:global_vars.h、global_vars.cpp content.h content.cpp main.cpp。

global_vars.h

#ifndef global_vars_h
#define global_vars_h

namespace Constants{

    extern const unsigned int b;

}

#endif

global_vars.cpp

#include "global_vars.h"

namespace Constants{

    extern const unsigned int b(5);


}

内容.h

#ifndef CONTENT_H_
#define CONTENT_H_

#include "global_vars.h"
#include <bitset>

struct a{

    std::bitset<Constants::b> s;
    int a=10;

};

#endif

内容.cpp

#include "content.h"

a xVar;

main.cpp

#include "content.h"
int main(){
   return 0;
}

我收到以下错误:

In file included from content.cpp:1:0:
content.h:11:31: error: the value of ‘Constants::b’ is not usable in a constant expression

In file included from content.h:4:0,
from content.cpp:1:
global_vars.h:6:28: note: ‘Constants::b’ was not initialized with a constant expression
extern const unsigned int b;

我还必须在 content.cpp/.h(对于其他位集)以外的文件中使用 Constants::b,那么我该如何解决这个问题呢?感谢您的帮助。

谢谢

最佳答案

你问的是不可能的。

在 C++ 中,模板完全由编译器解析,链接器只能看到模板类和函数的完全实例化的主体。编译器只能看到给定编译单元中的代码。

因此,即使 intextern const 并在某个编译单元中赋值(使其在运行时有效),它也不可能用作任何其他编译单元中的模板参数。编译器在解析哪些模板实例化引用相同类型时无法知道该 int 的值。

最有可能得到的最接近的是,您可以将指向该 int 的指针作为模板参数,然后如果您有例如使用在运行时运行的模板参数的函数,它可以取消引用指针以获取常量值。如果您启用了链接时优化,它甚至可能会内联它,我不确定。

关于c++ - 如何在不同文件中使用 C++ extern 常量作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32381824/

相关文章:

c++ - 如何分析 VS2010 在 Debug模式下捕获的未处理异常?

c++ - 为 vector : template parameters not deducible in partial specialization 定义散列

c++ - 将 const 左值引用作为右值引用传递

没有模板函数继承的 C++ 接口(interface)

c - C 中全局变量的行为

c++ - 通过引用传递 const 值

c++ - 计算合并排序算法的交换/比较次数

c - 为什么 stdlib.h 充满了外部函数原型(prototype)和 gcc 对此的差异

c++ - extern 模板不适用于 gcc?

c++ - 为什么rand()继续赋予相同的值?