c++ - C ++枚举到模板化函数
问题描述
我有一个枚举类,我有一堆非常相似的代码,可以将枚举转换为模板函数调用:
auto func1(Type type, ...params)
{
switch (type)
{
case Type::typeA: return func1<Type::typeA>(params);
case Type::typeB: return func1<Type::typeB>(params);
case Type::typeC: return func1<Type::typeC>(params);
...
}
}
auto func2(Type type, ...params)
{
switch (type)
{
case Type::typeA: return func2<Type::typeA>(params);
case Type::typeB: return func2<Type::typeB>(params);
case Type::typeC: return func2<Type::typeC>(params);
...
}
}
// more such func3, func4, ...
#define
我可以使用宏生成此代码。我可以用模板做任何事情吗?我可以为每个枚举类型创建一个模板类,每个类都包含所有函数。但是如何通过名称调用该函数?
解决方案
您可能会执行以下操作:
template <typename Func, typename... Params>
auto visit(Func func, Type type, Params&&... params)
{
switch (type)
{
case Type::typeA:
return func(std::integral_constant<Type, Type::typeA>{}, std::forward<Params>(params)...);
case Type::typeB:
return func(std::integral_constant<Type, Type::typeB>{}, std::forward<Params>(params)...);
case Type::typeC:
return func(std::integral_constant<Type, Type::typeC>{}, std::forward<Params>(params)...);
//...
}
}
调用类似于:
visit([](auto t, int e){ return Func1<t()>(e); }, type, 42);
推荐阅读
- scala - Spark Structured Streaming MemoryStream + Row + Encoders 问题
- java - 通过 gremlin java 客户端将数据远程推送到 Azure Cosmos db 时出错
- android - 对不同的按钮使用相同的活动,但使用 xml 资源执行不同的操作
- javascript - 为什么滚动时我的粘性导航栏的高度会消失?
- javascript - 在对象属性中拆分字符串并创建新数据集
- python - 一堆立方体的体积
- sabre - 调用 Sabre BargainFinderMax REST API 时出错 — ERR.2SG.PROVIDER_TIMEOUT
- python - url 未定义,在 python 和 selenium 中
- android - PopupMenu - 如何?
- android - camera2 大小的表面视图