如何将枚举传递到模板参数
How to pass an enum to a template parameter
我有一个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内的子积分中;无法避免。
相关文章:
- 有没有办法使用类的私有枚举值作为模板参数?
- 从可变参数创建枚举?
- 在运行时使用枚举器值作为模板函数的模板参数的元程序
- 基于枚举参数调用专用模板方法
- 枚举作为模板参数
- 如何将枚举类作为类模板参数包含在内?
- 如何从枚举类值中指定模板函数参数中的数组大小?
- 是否可以使用泛型枚举类型作为函数的参数?
- C++ - 使用模板类中的枚举而不带模板参数
- 将函数参数限制为某些枚举值
- C++ 成员函数的多个定义,基于枚举模板参数
- 如何根据枚举参数返回其他类型
- 枚举类别和布尔模板参数的放松constexpr要求
- C++ 在C++中通过引用将枚举作为默认参数传递时出错
- 不能将类实例化为 LHS 值,并将限定枚举作为参数 (C++ VS2015)
- 是否可以使用 static_cast 从可变参数枚举创建 boost::mpl::list_c
- 枚举作为基类的模板参数总是会因未解决的错误而失败
- 在模板参数内向前声明枚举类
- C++运行时从编译时已知集/枚举中选择模板非类型参数
- 有没有一种方法可以在基于枚举的可变参数模板函数之间进行选择,这比将函数包装在结构中更简单