#include<bits/stdc++.h>
using namespace std;
struct task_base
{
virtual ~task_base () {}
virtual void operator()()const=0;
};
template<typename F>
struct task_model:public task_base
{
F functor_;
template<typename U>
task_model(U &&f):functor_(forward<U>(f))
{
}
void operator()()const override
{
functor_();//函数是自带()的
}
};
struct node
{
void operator()()const
{
// cout<<"AK"<<endl;
};
};
void f()
{
cout<<"AK"<<endl;
}
class my_task
{
vector<task_base*>A ;
public:
template<typename F>
my_task(F&& f)
{
using model_type=task_model<F>;
A.push_back (new model_type(forward<F>(f)));
}
~my_task()
{
for(int i=0; i<A.size(); i++)
delete A[i];
A.clear();
}
void operator()()const
{
(*A[0])();
}
};
int main()
{
node A;
task_model<void(*)()> t1{&f};
t1();
my_task t2{&f};
t2();
}
这份代码里面的坑点主要是在往vector里面塞基类的时候,需要以指针的形式放进去,这样才能访问到他的子类,因为在实现类的多态的时候,有一个叫虚函数表的东西,这个东西本身也是一个指针。