如何将枚举传递到模板参数

How to pass an enum to a template parameter

本文关键字:参数 枚举      更新时间:2023-10-16

我有一个XML,我可以从需要创建的对象类型中阅读,问题在于我如何通过枚举而无需使用switch/if语句。

   enum ObjectType {A,B,C};
   void parseXML(const string& fileName)
   {
     //Open-read file etc...
     ObjectType objType = xmlObject.type(); <- the structure provided from the xml parser that I use(codesynthesis)
     ObjectParameters params = gatherParameters(xmlObject);
     auto createdObj = factory.createObject<objType>(params);
                                           ^^^^^
  }

需要一个恒定的表达式,所以我必须映射提供的类型还是有任何更快的方法?如果是这样,是否可以将枚举用作类的标签/同义词?

auto magic_switch=[]( auto value, auto limit ){ // limit must be compile time type value
  return [value,limit](auto&&f){
    auto* pf=std::addressof(f);
    using ptr=decltype(pf);
    auto index=indexer<limit>();
    using R=decltype((decltype(f)(*pf))(limit));
    using Sig=R(*)(ptr pf);
    static const auto table=index(
      [](auto...Is)
      ->std::array<Sig, decltype(limit){}>
      {
        return {{
          +[](ptr pf)->R
          {
            return (decltype(f)(*pf))( decltype(Is){} );
          }...
        }};
      }
    );
    return table[value](pf);
  };
};

其中索引是

template<std::size_t I>using index_t=std::integral_constant<std::size_t, I>;
template<std::size_t I>constexpr index_t<I> index_k{};
template<class=void, std::size_t...Is>
auto indexer(std::index_sequence<Is...>){
  return [](auto&&f){
    return f( index_k<Is>... );
  };
}
template<std::size_t N>
auto indexer(){
  return indexer(std::make_index_sequence<N>{});
}

然后您的代码;

auto createdObj = factory.createObject<objType>(params);
// work with it

变为:

magic_switch( objType, index_k<3> )
([&](auto index){
  auto createdObj = factory.createObject<(ObjectType)index>(params);
  // work with it
});

现场示例。

请注意,您最终会在lambda内的子积分中;无法避免。