其类似于C/C++中函数名或者函数的取地址操作,在C/C++中函数的作为参数的传递,可以通过函数名func或者&func的形式作为参数。
matlab code:
data=load('../train_task_data.mat','train_task_data');
train_task_data=data.train_task_data;
opt.lossType='square'; % hinge , square
if strcmp(opt.lossType,'hinge')
grad=compute_gradient2(@hinge,train_task_data);
elseif strcmp(opt.lossType,'square')
grad=compute_gradient2(@square,train_task_data);
end
disp('over...');
function grad=compute_gradient2(func,train_task_data)
%do some common work
%..........
% call
grad=func(train_task_data);
end
c++ code
#include "stdafx.h"
#include<iostream>
using namespace std;
float hinge(float *train_task_data)
{
cout << "hinge function" << endl;
return 0;
}
float square(float *train_task_data)
{
cout << "square function" << endl;
return 1;
}
float compute_gradient2(float loss_func(float*), float *train_task_data)
{
float grad=loss_func(train_task_data);
return grad;
}
int main()
{
float train_task_data[5] = { 1,2,3,4,5 };
float grad1 = compute_gradient2(hinge, train_task_data);
//或者
float grad2 = compute_gradient2(&hinge, train_task_data);
return 0;
}