C ++:基于枚举将调度分解为模板化成员函数

时间:2018-01-15 02:41:52

标签: c++ templates

我有以下代码,我试图将switch语句分解为将enum转换为模板化函数调用。

我设法通过引入帮助程序类来实现它,但结果不是很简单或漂亮。

你能想到一个更优雅的解决方案吗?

#include <iostream>

enum Type {kA, kB};

struct A {
    static void process(int arg) { std::cerr << "A::process(" << arg << ")\n"; }
};

struct B {
    static void process(int arg) { std::cerr << "B::process(" << arg << ")\n"; }
};

// This is the original struct which contains the switch statement.
// However I have several such classes and methods, so I would like to
// factor out the switch().
struct S1 {
    template <typename T> void templated_func(int arg) {
        T::process(arg + 10 + i_);
        T::process(arg + 20 + i_);
    }
    void func(Type type, int arg) {
        switch (type) {
         case kA:
            templated_func<A>(arg);
            break;
         case kB:
            templated_func<B>(arg);
            break;
        }
    }
    int i_ = 100;
};


// This function call dispatches to a templated helper class based
// on the value of the enum type.
template <template <typename T> class HelperClass, typename... Args>
void dispatch(Type type, Args&&... args) {
    switch (type) {
     case kA:
        HelperClass<A>::method(std::forward<Args>(args)...);
        break;
     case kB:
        HelperClass<B>::method(std::forward<Args>(args)...);
        break;
    }
}

// It works but the result is not simple or pretty.  Can it be made simpler somehow?
struct S2 {
    template <typename T> void templated_func(int arg) {
        T::process(arg + 10 + i_);
        T::process(arg + 20 + i_);
    }
    template <typename T> struct Helper_func {
        static void method(S2* pthis, int arg) {
            pthis->templated_func<T>(arg);
        }
    };
    void func(Type type, int arg) {
        dispatch<S2::Helper_func>(type, this, arg);
    }
    int i_ = 100;
};

int main() {
    S1 s1;
    s1.func(kA, 1);             // prints A::process(111), A::process(121)
    S2 s2;
    s2.func(kB, 2);             // prints B::process(112), B::process(122)
}

0 个答案:

没有答案