Search code examples
c++templatesc++11argument-passing

Pass a template method as an argument


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) << std::endl;

This function gets the function as a template type and calls it on an object

template <typename F>
double process_time(F algorithm)
{
    Model model;
    double time=0;
    do
    {
        // ...
        time += model.algorithm(arg1);
    } while (! stop_criteria);
    return time;
}

Note that method1 is a function template as well:

template <typename T>
double method1(std::vector<T> &v)
{
    ...
}

What is the legal syntax for it?

main.cpp

#include <iostream>
#include <vector>

class Model
{
public:

    template <typename T>
    double method1(std::vector<T> &v)
    {
        double t = 0;
        //...
        return t;
    }

    template <typename T>
    double method2(std::vector<T> &v)
    {
        double t = 0;
        //...
        return t;
    }

};

template <typename F>
double process_time(F algorithm)
{
    Model model;
    double time = 0;
    bool stop_criteria = false;
    do
    { 
        std::vector<int> arg1;
        // ...
        time += model.algorithm(arg1);
    } while (!stop_criteria);
    return time;
}

int main()
{
    std::cout << process_time(Model::method1) << std::endl;
    return 0;
}

Solution

  • This is the closest to your code that compiles:

    #include <iostream>
    #include <vector>
    
    struct Model {
      template <typename T>
      double method1(std::vector<T> &v) {
        double t = 0;
        //...
        return t;
      }
    };
    
    template <typename F>
    double process_time(F algorithm) {
        Model model;
        double time = 0;
        bool stop_criteria = false;
        do
        { 
            std::vector<int> arg1;
            // ...
            time += (model.*algorithm)(arg1);
        } while (!stop_criteria);
        return time;
    }
    
    int main() {
      std::cout << process_time(&Model::method1<int>) << std::endl;
    }