我遇到了这样一个技巧:
// This template utilizes the One Definition Rule to create global arrays in a header.
template<typename unused=void>
struct globals_struct
{
static const uint8 s_str_serialize_flags[256];
// ...
};
typedef globals_struct<> globals;
template<typename unused>
const uint8 globals_struct<unused>::s_str_serialize_flags[256] =
{
// ... data here ...
};
// ... and then the array is accessible as:
uint8 value = globals::s_str_serialize_flags[index])
此代码来自 Rich Geldreich 的 Purple JSON我从乍得奥斯汀的 blog 那里了解到的.
在看到这段代码之前,我认为在一个只有头文件的库中拥有一个数组的唯一方法是要求用户在一个文件中#define
一个神奇的宏(在包含头文件之前).
所以我喜欢模板包装技巧,但我想知道:
- 它是 C++ 习语吗(它有名字)吗?
- 它是否符合标准且使用安全?
- 这样的模板包装是在 header 中包含数组的最简单方法吗?
编辑: 我刚刚在 SO answer 中遇到了同样的把戏它显示为 C++17 内联变量的替代方案。
最佳答案
对我来说最简单的就是把它包装成一个函数(和std::array
)
using arr256 = std::array<std::uint8_t, 256>;
inline constexpr arr256 s_str_serialize_flags() {
constexpr arr256 values = {/**/};
return values;
}
或者没有constexpr
约束:
using arr256 = std::uint8_t[256];
inline const arr256& s_str_serialize_flags() {
static const arr256 values = {/**/};
return values;
}
关于c++ - 在 header 中定义全局数组的模板技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46099523/