首页 > 解决方案 > 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我可以使用宏生成此代码。我可以用模板做任何事情吗?我可以为每个枚举类型创建一个模板类,每个类都包含所有函数。但是如何通过名称调用该函数?

标签: c++templatesenums

解决方案


您可能会执行以下操作:

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);

演示


推荐阅读