#ifndef PINK_FUNCTION_H
#define PINK_FUNCTION_H
template<typename R, class... Arg0>
class function{
public:
function(R(*fun)(Arg0...)) {
__calltable<R(*)(Arg0...)>* table = new __calltable<R(*)(Arg0...)>(fun);
this->base = (__callbase*)table;
}
R operator()(Arg0... arg) {
return (*base)(arg...);
}
~function() {
if (base) delete base;
}
private:
//base class
class __callbase{
public:
virtual R operator()(Arg0... arg) = 0;
virtual ~__callbase() {};
};
//define class
template<typename F>
class __calltable : __callbase{
public:
__calltable(F fun) {
fun_ = fun;
};
virtual R operator()(Arg0... arg) {
return fun_(arg...);
}
virtual ~__calltable() {};
private:
F fun_;
};
__callbase* base;
};
#endif
用法:
#include<stdio.h>
#include"mfunction.h"
int main() {
function<int, char, char> f([](char b, char c ){
printf("%d%d\n",b, c);
return 10;
});
f('c', 'a');
}
版权声明:本文为Pink_Brook原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。