如何为不同文件中的模板参数使用c++外部常量变量
How to use a C++ extern constant variable for a template argument in a different file
我有以下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);
}
content.h
#ifndef CONTENT_H_
#define CONTENT_H_
#include "global_vars.h"
#include <bitset>
struct a{
std::bitset<Constants::b> s;
int a=10;
};
#endif
content.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(对于其他bitsets),那么我如何才能做到这一点呢?谢谢你的帮助。
谢谢
你的要求是不可能的。
在c++中,模板完全由编译器解析,链接器只能看到模板类和函数的完整实例化体。编译器只能看到给定编译单元中的代码。
因此,即使int
是extern const
并在某个编译单元中赋值(使其在运行时有效),它也不可能在任何其他编译单元中用作模板参数。编译器在解析哪些模板实例化引用了相同的类型时,将无法知道该int
的值。
最接近你可以得到最有可能的,是你可以一个指针指向int
作为模板参数,然后,如果你有一个函数使用该模板参数在运行时运行,它可以解引用指针以获得常数值。如果您启用了链接时间优化,它甚至可能内联它,我不确定。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 如何将enable-if与模板参数和参数包一起使用