C++ 在标头中定义全局数组的模板技巧

C++ 在标头中定义全局数组的模板技巧,c++,global-variables,header-files,one-definition-rule,C++,Global Variables,Header Files,One Definition Rule,我遇到了这样一个诡计: // 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<&

我遇到了这样一个诡计:

// 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])
//此模板使用一个定义规则在标头中创建全局数组。
模板
结构全局\u结构
{
静态常量uint8 s_str_序列化_标志[256];
// ...
};
typedef globals_struct globals;
模板
const uint8 globals_struct::s_str_serialize_flags[256]=
{
//…这里的数据。。。
};
// ... 然后可以通过以下方式访问阵列:
uint8 value=globals::s_str_serialize_标志[索引])
这段代码来自Rich Geldreich的,我从Chad Austin的中学到的

在看到这段代码之前,我认为在只有头的库中使用数组的唯一方法是要求用户在一个文件中定义一个魔法宏(在包含头之前)

所以我喜欢模板包装技巧,但我想知道:

    这是C++习语(有名字吗?< /LI>)
  • 它是否符合标准且使用安全
  • 这样的模板包装是在头中包含数组的最简单方法吗
编辑:
我只是在一个例子中遇到了同样的技巧,其中它显示为C++17内联变量的替代品。

对我来说,最简单的方法是将它包装到一个函数中(和
std::array


error:“values”在“constexpr”函数中声明为“static”
@marcin:Sad不允许这样做:-/alternative修复(保留
constexpr
)。
using arr256 = std::array<std::uint8_t, 256>;

inline constexpr arr256 s_str_serialize_flags() {
    constexpr arr256 values = {/**/};
    return values;
}
using arr256 = std::uint8_t[256];

inline const arr256& s_str_serialize_flags() {
    static const arr256 values = {/**/};
    return values;
}