|
发表于 2003-12-22 18:10:00
|
显示全部楼层
Re:这次希望有人能关注一下!谢谢各位大虾!!!
修改如下:
class A
{
public:
int printhello()
{
printf("Hello World!\n");
return 0;
}
};
int printhello()
{
printf("Hello World!\n");
return 0;
}
template<class R> //普通函数指针的处理类
class pointer_to_function {
public:
explicit pointer_to_function(R (*_X)()) : _ptr(_X) {}
R operator()() const {return (_ptr()); }
private:
R (*_ptr)();
};
//要注意我们必须得到实例化对象的副本
template<class R,class Class> //成员函数指针的处理
class pointer_to_mem_function {
public:
explicit pointer_to_mem_function(R (Class::*_Pm)(),Class* c) : _ptr(_Pm),_C(c){}
R operator()() const {return ((_C->*_ptr)()); }
private:
R (Class::*_ptr)();
Class* _C;
};
template<class R, class _C> inline //成员函数的辅助函数
pointer_to_mem_function<R, _C> mem(R (_C::*_P)(),_C* c )
{ return (pointer_to_mem_function<R, _C>(_P,c)); }
template<class R> inline //函数指针的辅助函数
pointer_to_function<R>
ptr(R (*_X)())
{ return (pointer_to_function<R>(_X)); }
class Engine
{
public:
Engine():m_pf(printhello),m_pmf(&Engine::print,this)
{
}
template<class _Fn> inline
void each(_Fn _Op) { _Op();}
int print(){ printf("Hello World!\n"); return 0; }
Init() //初始
{
// each(ptr(printhello));
// each(mem(&Engine::print,this));
}
show() //显示
{
}
_main() //主判断循环
{
m_pf();
m_pmf();
}
pointer_to_function<int> m_pf;
pointer_to_mem_function<int,Engine> m_pmf;
};
int main(int argc, char* argv[])
{
Engine engine;
engine.Init();
engine._main();
return 0;
}
/*
我不想在
Init()
{
each(ptr(printhello));
each(mem(&Engine::print,this));
}
中执行显示hello world的语句。
我只想让他们在某个条件下显示。
如:
_main()
{
if(flag==1)
//执行显示
//而这里的显示不需要麻烦的使用each(ptr(printhello));
//而只是简单的使用show()即可。
//相当于 each(ptr(printhello));是设置
//而show()就是执行
}
思想有点类似于:
class A{
public:
//...
int (*m_pProcessFunc)();
bool SetProcessFunc(int (*Func)()) { m_pProcessFunc =Func; return true; }
int do(){ if(m_pProcessFunc) m_pProcessFunc(); }
};
int dosome()
{ return 0; }
这样我们就可以
A a;
a.SetProcessFunc(dosome);
然后在调用的时候就
a.do();
谢谢!
因为如果用
int (*m_pProcessFunc)();
bool SetProcessFunc(int (*Func)()) { m_pProcessFunc =Func; return true; }
这样不能保存类成员函数地址!
但是使用了函数对象,因为保存的只是对象~
而不是对象的指针,所以只是一个暂态的过程
怎么存储呢?
*/ |
|