gpt4 book ai didi

c++ - 如何将 C++ 外部常量变量用于不同文件中的模板参数

转载 作者:搜寻专家 更新时间:2023-10-31 02:20:41 25 4
gpt4 key购买 nike

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

全局变量.h

#ifndef global_vars_h
#define global_vars_h

namespace Constants{

extern const unsigned int b;

}

#endif

全局变量.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;

主要.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++ 外部常量变量用于不同文件中的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32381824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com