variadic templates with template function names

前端 未结 5 1108
悲哀的现实
悲哀的现实 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:54

    Here is another, more compact solution that compiles in C++11:

    #include 
    #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 run() {
            int arr[] = { 0, ((this->*M)(), 0)... };
            (void)arr;
        }
    
    public:   
        void update() {   
            run<&SensorType::update...>();
        }
    
        void printStats() {
            run<&SensorType::printStats...>();
        }
    };
    
    int main() {
        BaseSensor bs;
        bs.update();
        bs.printStats();
    }
    

    I would be tempted to say that you don't need any structure to support the pack of pointers to member methods.
    Anyway, I found that this compiles with clang and it doesn't work with GCC. I'm still trying to figure out if the code is ill-formed or if the problem is in the compiler.

    I'd suggest to follow the other question to know if you can use or not this code.

提交回复
热议问题