Pass a template method as an argument

前端 未结 3 806
后悔当初
后悔当初 2021-01-22 03:58

Could some one help me how to implement this code?

I need to pass a function to another function:

std::cout << process_time(Model::method1) <<         


        
3条回答
  •  深忆病人
    2021-01-22 04:47

    Change your process time line with time += to:

       time += algorithm(&model,arg1);
    

    then call it with:

    std::cout << process_time([](Model* m, std::vector& v){return m->method1(v);}) << std::endl;
    

    or in C++14:

    std::cout << process_time([](Model* m, auto& v){return m->method1(v);}) << std::endl;
    

    which leaves the choice of what kind of vector it will pass to method1 up to process_time instead of fixing it at the calling site.

    Basically, this avoids dealing with pointer-to-member variables. Instead, the algorithm in process_time is just a map from Model x vector to double. This also means that we can have a non-member algorithm.

    If you don't like the verbosity of the above at the call site, you can keep the changes to process_time and change the call to:

    std::cout << process_time(std::ref(&Model::method1)) << std::endl;
    

    as std::ref takes a pointer to a member function, and returns a callable object that takes a pointer-to-Model as the first argument, and std::vector& as the second. Which matches how we use it.

提交回复
热议问题