[英]C++: Header-only project, static const non-integral
I have a header-only project .我有一个仅限标题的项目。 Inside it I have a class.在里面我有一堂课。 Inside it (or anywhere else actually) I would like to have constant data (enum values to string and vice-verse).在它里面(或其他任何地方),我想要常量数据(字符串的枚举值,反之亦然)。 This problem seems a lot harder that I expected.这个问题似乎比我预期的要困难得多。
typedef boost::bimap<MyEnum,std::string> Data;
What I tried and did not work:我尝试过但没有用的:
static Data const s_data = _initData();
: Error is like: only static const integral data members can be initialized within a class
. : 错误就像: only static const integral data members can be initialized within a class
。
static Data const * const s_pData = _initData();
: The _initData()
function had a static local variable (which became filled on first call), and returned the address of it. : _initData()
函数有一个静态局部变量(在第一次调用时被填充),并返回它的地址。 Did not work with the same reason as above.没有与上述相同的原因工作。
What I tried and worked, but I consider it ugly:我尝试和工作的东西,但我认为它很丑陋:
class Ugly {
public:
static MyEnum lookupByName(std::string s)
{
MyEnum ret;
lookup(ret,s,true);
return ret;
}
static String lookupByEnum(MyEnum e)
{
std::string ret;
lookup(e,ret,false);
return ret;
}
static void lookup(MyEnum &e, std::string &s, bool etos)
{
static Data s_data = _fill();
if(etos)
s = /* ... */;
else
e = /* ... */;
}
static Data _fill(){ /* ... */ };
};
Ideas?想法?
The simpler is更简单的是
static T& global_t()
{ static T z = initializer; return z; }
global_t()
can be used whereve a T value is required. global_t()
可用于需要 T 值的地方。
NOTE : In answer to rioki comment, we must also specify the function as inline
if it is at global or namespace level (to avoid the "multiple instances" problem towards the linker).注意:为了回答 rioki 评论,我们还必须将函数指定为inline
函数,如果它是在全局或命名空间级别(以避免链接器的“多实例”问题)。
The inline keyword is not necessary if the function is a template or is a class member-function (for which the inline definition is by default)如果函数是模板或类成员函数(默认为内联定义),则不需要 inline 关键字
If the static T
instantiation must be shared among different OS modules (read: DLLs) rioki is perfectly right, but -at that point- a header-only library makes no more sense.如果static T
实例化必须在不同的 OS 模块(读取:DLL)之间共享,rioki 是完全正确的,但是 - 在这一点上 - 仅头文件库没有任何意义。
Starting from C++17, the inline
specifier can also be used on variables.从 C++17 开始, inline
说明符也可以用于变量。
So, from C++17 onward, you can just write所以,从 C++17 开始,你可以只写
inline T global_object = initializer;
You can also use inline for static members of function, to provide inline initialization, like您还可以对函数的静态成员使用内联,以提供内联初始化,例如
class Class
{
static inline Type static_object_name = initializer;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.