/*note
请使用g++ 2.95 or higher, intel c++ 5.0 or higher (6.0 has been released)
编译,其他主流编译器无法正确通过, vc 居然出现 26 处错误 */
#include < iostream >
#include < utility > //
含 pair 和 make_pairusing namespace std;
template <typename t>
struct memfunctraits { };
//partial specialization 1
template < typename r, typename o >
struct memfunctraits< r (o::*)() /*
指向成员函数指针 */ > { typedef r returntype;
typedef o objecttype;
};
//partial specialization 2
template < typename r, typename o >
struct memfunctraits< r (o::*)() const /*
指向成员函数 const 的指针 */ > { typedef r returntype;
typedef o objecttype;
};
//partial specialization 3
template < typename r, typename o, typename p1 >
struct memfunctraits< r (o::*)(p1) /*
指向具有参数类型的成员函数指针 */ > { typedef r returntype;
typedef o objecttype;
};
//partial specialization 4
template < typename r, typename o, typename p1 >
struct memfunctraits< r (o::*)(p1) const /*
指向具有参数类型的 const 成员函数指针 */ > { typedef r returntype;
typedef o objecttype;
};
template < typename memfuncptrtype >
class pmfc {
public:
typedef typename memfunctraits<memfuncptrtype>::objecttype objecttype;
typedef typename memfunctraits<memfuncptrtype>::returntype returntype;
typedef std::pair<objecttype*, memfuncptrtype> callinfo;
pmfc(const callinfo& info) : _callinfo(info) { } //init
//
支持无参数类型,returntype = memfuncpretype returntype operator()() const
{ return (_callinfo.first->*_callinfo.second)(); }
// 支持具有参数类型
template <typename param1type>
returntype operator()(param1type p1) const
{ return (_callinfo.first->*_callinfo.second)(p1); }
private:
callinfo _callinfo;
};
template <typename t>
class smartptrbase {
public:
smartptrbase(t *p) : ptr(p) { } //init
//partial specialization pmfc
并 重载 operator->*. template <typename memfuncptrtype>
const pmfc<memfuncptrtype> operator->*(memfuncptrtype pmf) const
{ return std::make_pair(ptr, pmf); }
private:
t* ptr;
};
template <typename t>
class sp : private smartptrbase<t> { // g++ 3.04
都有错误,改为 public,估计是一个 bug。intel c++没有错误。public:
sp(t *p) : smartptrbase<t>(p) { }
using smartptrbase<t>::operator->*;
};
class wombat {
public:
int dig() { cout << "digging..." << endl; return 1; }
int sleep() { cout << "sleeping..." << endl; return 5; }
int eat() const { cout << "eatting..." << endl; return 7; }
int move(int op) { cout << "moving..." << endl; return 9; }
};
typedef int (wombat::*pwmf)();
typedef int (wombat::*pwmfc)() const;
typedef int (wombat::*pwmf1)(int);
main()
{
sp<wombat> pw = new wombat;
pwmf pmf = &wombat::dig;
(pw->*pmf)(); // digging...
pmf = &wombat::sleep;
(pw->*pmf)(); // sleeping...
pwmfc pmfc = &wombat::eat;
(pw->*pmfc)(); // eatting...
pwmf1 pmf1 = &wombat::move;
(pw->*pmf1)(2); // eatting...
return 0;
}
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器