我有一个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);
^^^^^
}需要一个常量表达式,所以我必须映射所提供的类型还是有更快的方法?如果是这样的话,是否有办法将枚举用作类的标记/同义词?
发布于 2016-12-20 13:12:57
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中的子范围中结束;这是无法避免的。
https://stackoverflow.com/questions/41242745
复制相似问题