首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cereal:跨枚举的共享序列化函数

Cereal:跨枚举的共享序列化函数
EN

Stack Overflow用户
提问于 2017-03-08 23:22:55
回答 1查看 223关注 0票数 0

假设我有这样的东西:

代码语言:javascript
复制
enum t_color { BLUE=0,RED,GREEN};
vector<string> TAG_color={"BLUE", "RED", "GREEN"};

enum t_colores { AZUL=0,ROJO,VERDE};
vector<string> TAG_colores={"AZUL", "ROJO", "VERDE"};

我想(在谷类中)使用一个通用的save_minimal,比如:

代码语言:javascript
复制
  template <class Archive,typename T > inline
  std::string save_minimal( Archive const &, typename std::enable_if< std::is_enum<T>::value, T >::type const & t )
  {
    std::string ret="Unknown";
    if ( std::is_same<T,t_color>::value)
    {
      ret=TAG_color[t];
    }
    else if (  std::is_same<T,t_colores>::value)
    {
      ret=TAG_colores[t];
    }
    return ret;
 }

它会编译,但看起来像是谷类忽略了模板。它只使用枚举的“整型”值。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-09 16:52:25

是的..。这是可行的(但不是直接通过谷类食品):

代码语言:javascript
复制
#define SERIALIZE_ENUM(enumname)                                               \
template <class Archive> inline                                                \
std::string save_minimal( Archive const &, t_##enumname const & t )            \
{                                                                              \
  return std::string(TAG_##enumname[t]);                                       \
}                                                                              \
template <class Archive> inline                                                \
void load_minimal(Archive const&, t_##enumname & t,std::string  const& value ) \
{                                                                              \
  int a=0;                                                                     \
  for (auto const &tag:TAG_##enumname)                                         \
  {                                                                            \
    if ( tag == value )                                                        \
    {                                                                          \
      t = static_cast<t_##enumname>(a);                                        \
      return;                                                                  \
    }                                                                          \
    a++;                                                                       \
  }                                                                            \

namespace cereal { 
  SERIALIZE_ENUM(color)
  SERIALIZE_ENUM(colores)
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42675226

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档