传递模板方法作为参数 [英] Pass a template method as an argument

查看:55
本文介绍了传递模板方法作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我实现该代码吗?

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;
}

请注意,方法1 也是一个功能模板:

Note that method1 is a function template as well:

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

它的法律语法是什么?

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;
}


推荐答案

这是最接近您的编译的代码:

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;
}

这篇关于传递模板方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆