如何为不同文件中的模板参数使用c++外部常量变量

How to use a C++ extern constant variable for a template argument in a different file

本文关键字:参数 c++ 外部 变量 常量 文件      更新时间:2023-10-16

我有以下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++中,模板完全由编译器解析,链接器只能看到模板类和函数的完整实例化体。编译器只能看到给定编译单元中的代码。

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

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