C++ 定义跨文件常量的最佳方法
我正在开发一款游戏,有一个有趣的问题。 我想在一个文件中实现一些游戏范围的常量值。 现在我有这样的东西:
constants.cppconstants.hpp
extern const int BEGINNING_HEALTH = 10;
extern const int BEGINNING_MANA = 5;
”
extern const int BEGINNING_HEALTH;
extern const int BEGINNING_MANA;
然后文件只是#include“constants.hpp 这非常有效,直到我需要使用其中一个常量作为模板参数,因为外部链接常量不是有效的模板参数。 所以我的问题是,实现这些常量的最佳方法是什么? 恐怕简单地将常量放入头文件中会导致它们在每个翻译单元中定义。 而且我不想使用宏。
谢谢
I am working on a game and have an interesting question. I have some game-wide constant values that I want to implement in one file. Right now I have something like this:
constants.cpp
extern const int BEGINNING_HEALTH = 10;
extern const int BEGINNING_MANA = 5;
constants.hpp
extern const int BEGINNING_HEALTH;
extern const int BEGINNING_MANA;
And then files just #include "constants.hpp"
This was working great, until I needed to use one of the constants as a template parameter, because externally-linked constants are not valid template parameters.
So my question is, what is the best way to implement these constants? I am afraid that simply putting the constants in a header file will cause them to be defined in each translation unit. And I don't want to use macros.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
去掉
extern
就可以了。该代码在标头中工作得很好,因为一切都是“真正恒定的”,因此具有内部链接:
该代码不能安全地放入头文件中,因为每一行都有外部链接(显式地或因为不是真正恒定的):
Get rid of the
extern
and you're set.This code works perfectly fine in a header, because everything is "truly constant" and therefore has internal linkage:
This code cannot safely be put in a header file because each line has external linkage (either explicitly or because of not being truly constant):
枚举怎么样?
常量.hpp
How about enums?
constants.hpp
在您的 .hpp 文件中使用“static const int”,并且在 .cpp 文件中不放置任何内容(当然,您在那里的任何其他代码除外)。
Use "static const int" in your .hpp file, and put nothing in the .cpp file (except whatever other code you have there of course).
利用命名空间:
然后你可以使用player.health = GameBeginning::HEALTH;
make use of namespaces:
then u can use as player.health = GameBeginning::HEALTH;
大多数编译器根本不为 const POD 值分配空间。 他们对它们进行了优化,并将它们视为已经被
#define
d 处理,不是吗?Most compilers simply don't allocate space for const POD values. They optimize them out and treat them as if they had been
#define
d, don't they?一个简单的人发生了什么:
伙计,那些日子过去了。
哦等等,那些仍然的日子!
What ever happened to a simple:
Man, those were the days.
Oh wait, those still are the days!
也许类似于静态类的东西?
perhaps something along the lines of a static class?
作为标题问题的快速回答,单例模式可能是定义跨文件常量并确保对象只有一个实例的最佳 C++ 方法。
至于模板参数问题,您需要传递类型而不是值。 你的类型是“int”。
As a quick answer to the title question, a singleton pattern is a possible best, C++ way to define cross-file constants and insure only one instance of the object.
As far as the template parameter problem, you need to pass a type not a value. Your type is "int".