variadic templates with template function names

前端 未结 5 1104
悲哀的现实
悲哀的现实 2021-01-14 18:14

following this question , I am trying to avoid copy-pasting some code related to calling all of the same-named methods of the mixins of the class BaseSensor.

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-14 18:59

    You can use a generic lambda and a kind of inversion of control.
    It follows a minimal, working example:

    #include
    
    struct EdgeSensor
    {
        void update() { std::cout << "EdgeSensor::update" << std::endl; }
        void printStats() { std::cout << "EdgeSensor::printStats" << std::endl; }
    };
    
    struct TrendSensor
    {
        void update() { std::cout << "TrendSensor::update" << std::endl; }
        void printStats() { std::cout << "TrendSensor::printStats" << std::endl; }
    };
    
    template
    class BaseSensor : public SensorType ...
    {
        template
        void execute(F &&f) {
            int arr[] = { (f(static_cast(*this)), 0)..., 0 };
            (void)arr;
        }
    
    public:
        void update() {
            execute([](auto &t) { t.update(); });
        }
    
        void printStats() {
            execute([](auto &t) { t.printStats(); });
        }
    };
    
    int main() {
        BaseSensor ets;
        ets.update();
        ets.printStats();
    }
    

提交回复
热议问题