在C ++中执行任何类型和数量的参数的函数 [英] A function to execute any function with any types and numbers of parameter in C++

查看:107
本文介绍了在C ++中执行任何类型和数量的参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个函数接受任何类型的向量和函数作为参数。所传递的函数在执行时计时,并返回所得到的时间。使用传递的向量调用函数调用,但我想要做的是扩展调用,以便任何数量的参数可以与函数调用一起传递,并且可以使用任何数量的参数调用。函数的代码如下,并且在名为functions.h的文件中找到:

I currently have a function that accepts a vector of any type and a function as parameters. The function that is passed is timed on execution and the resulting time is returned. The function call is invoked with the passed vector, but what I'd like to do is extend the call so that any number of parameters can be passed with the function call and it can be invoked with any number of parameters. The code for the function is below and is found in a file called functions.h:

template<typename X, typename F>
double timer(std::vector<X> elements, F function) {
   clock_t tstart, tend;

   tstart = clock();
   function(elements);
   tend = clock();

   return ((double)tend - tstart) / CLOCKS_PER_SEC;
}

函数mean只是计算给定值的平均值矢量)。包括对定时器的调用的main.cpp文件在这里:

The function mean just computes the mean of the given values (which are also in a vector). The main.cpp file including the call to timer is here:

#include <cstdlib>
#include <algorithm>
#include <numeric>
#include <vector>
#include <cmath>
#include <ctime>
#include <iostream>
#include "functions.h"

int main(void) {
   std::vector<double> x;
   x.push_back(53.0);
   x.push_back(61.0);
   x.push_back(49.0);
   x.push_back(67.0);
   x.push_back(55.0);
   x.push_back(63.0);

   double time = timer(x, mean<double>);
   std::cout << time << std::endl;

   return 0;
}

我不知道如何,但我相信它可能在从main需要改变?可能类似于:

I don't know how but I believe it's possibly in the call from main that needs to be changed? Maybe to something like:

double time = timer(mean<double(x)>);

double time = timer(fakeFunction<double(x, y)>);

定时器功能将更新为以下内容:

Where the timer function would be updated to something like the following:

template<typename F>
double timer(F function) {
   clock_t tstart, tend;

   tstart = clock();
   function();
   tend = clock();

   return ((double)tend - tstart) / CLOCKS_PER_SEC;
}

任何帮助或提示都将非常感谢。

Any help or tips would be greatly appreciated.

推荐答案

您可以使用 std :: bind 将参数绑定到回调:

You can use std::bind to bind the arguments to the callback:

double time = timer(std::bind(mean<double>, x));

这篇关于在C ++中执行任何类型和数量的参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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