【问题标题】:C++ enums into templated functionC ++枚举到模板化函数
【发布时间】:2020-03-30 05:02:10
【问题描述】:

我有一个枚举类,我有一堆非常相似的代码,可以将枚举转换为模板函数调用:

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

【问题讨论】:

  • 显示宏解决方案,更清楚您需要什么。还要对您需要的内容进行更多解释。如果显示的代码与您的问题相关,请创建一个干净的 minimal reproducible example 而不是包含多个 ... 的内容。

标签: c++ templates enums


【解决方案1】:

你可能会这样做:

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

Demo

【讨论】:

    【解决方案2】:

    您可以将func1/2/3 作为模板模板参数传递并将调用转发给该参数。

    typename <template <typename> typename Func, typename... Params>
    auto switchFunction(Type type, Params&&... params) {
        switch (type)
        {
        case Type::typeA: return Func<Type::typeA>(std::forward<Params>(params)...);
        case Type::typeB: return Func<Type::typeB>(std::forward<Params>(params)...);
        case Type::typeC: return Func<Type::typeC>(std::forward<Params>(params)...);
        ...
        }
    }
    

    然后你就这样使用它

    auto someOtherFunc(Type type, int param1, double param2)
    {
        return switchFunction<func1>(type, param1, param2);
    }
    

    为此,func1 的所有版本都必须返回相同的类型。

    此外,对func1 的所有调用都必须有效。不只是开关选择的那个。

    【讨论】:

    • OP 还必须在模板类中转换模板函数。
    猜你喜欢
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多