当C++模板参数遇上数组时

项目中针对API调用的错误码有对应的错误描述。
一个GetErrorDescriptionByErrorCode接口用于根据错误码获取错误描述信息。
错误码和错误描述被定义在一个以{错误码,错误描述}为元素的静态数组中:

static ErrorInfo g_errorInfoChs[]{
   {E_FAIL, "错误"},
   {E_SUCCESS, "成功"},
   ...
};

程序中,我需要将多种语言的信息,如中文,英文,日文等等,于是我定义了语言类型枚举,并又创建g_errorInfoEng和g_errorInfoJpn等。
我需要将信息注册到内存中去,于是要写一个注册函数。
考虑到要将数组作为函数参数,而且数组长度又不固定,最好写成模板函数的形式。
参考 https://www.cnblogs.com/kane1990/p/3260844.html
代码片段如下:

typedef struct
{
    ErrorInfo *info;
    int       size;
}ErrorElem;

std::map<LangType, ErrorElem> m_errorInformation;

template <size_t size>
inline void registerErrorInformation(LangType lang, ErrorInfo (&arr)[size])
{
     m_errorInformation.insert(make_pair(lang, ErrorInfo{arr, size}));
}

调用的时候,如下:

registerErrorInformation(E_CHINESE, g_errorInfoChs);
原文地址:https://www.cnblogs.com/MakeView660/p/12517938.html