Scott Meyes 是世界顶尖C++大师,著作有《Effective C++》,《More Effective C++》等,并发表许多著名评论和文章。
关键字:traits, partial specialization, 指向成员函数的指针, operator->*
DarkSpy 2002/4/24
/*NOTE
请使用g++ 2.97 or higher,
Intel C++ 5.0 or higher (6.0 beta for DarkSpy only [DarkSpy report bug])
编译,其他主流编译器无法正确通过, VC 居然出现 26 处错误 */
#include
#include // 包含 pair 和 make_pair
using namespace std;
template
strUCt MemFuncTraits { };
//partial specialization 1
template
struct MemFuncTraits {
typedef R ReturnType;
typedef O ObjectType;
};
//partial specialization 2
template
struct MemFuncTraits {
typedef R ReturnType;
typedef O ObjectType;
};
//partial specialization 3
template
struct MemFuncTraits {
typedef R ReturnType;
typedef O ObjectType;
};
//partial specialization 4
template
struct MemFuncTraits {
typedef R ReturnType;
typedef O ObjectType;
};
template
class PMFC {
public:
typedef typename MemFuncTraits ::ObjectType ObjectType;
typedef typename MemFuncTraits ::ReturnType ReturnType;
typedef std::pair CallInfo;
PMFC(const CallInfo& info) : _callinfo(info) { } //init
// 支持无参数类型,ReturnType = MemFuncPreType
ReturnType operator()() const
{ return (_callinfo.first->*_callinfo.second)(); }
// 支持具有参数类型
template
ReturnType operator()(Param1Type p1) const
{ return (_callinfo.first->*_callinfo.second)(p1); }
private:
CallInfo _callinfo;
};
template
class SmartPtrBase {
public:
SmartPtrBase(T *p) : ptr(p) { } //init
//partial specialization PMFC 并 重载 operator->*.
template
const PMFC operator->*(MemFuncPtrType pmf) const
{ return std::make_pair(ptr, pmf); }
private:
T* ptr;
};
template
class SP : private SmartPtrBase {
// g++ 3.0.2 都有错误,改为 public,估计是一个 bug。Intel C++没有错误。
public:
SP(T *p) : SmartPtrBase (p) { }
using SmartPtrBase ::operator->*;
//强制将 private 继承的 operator->* 继承为 public 为 main 中调用。
};
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; }
[1] [2] 下一页
int move(int op) { cout << "Moving..." << endl; return 9; }
};
typedef int (Wombat::*PWMF)(); //for Wombat::dig(0, sleep()
typedef int (Wombat::*PWMFC)() const; //for Wombat::eat() const
typedef int (Wombat::*PWMF1)(int); //for Wombat::move()
main()
{
SP 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;
}
如果有不同意见或者有任何疑问可以和DarkSpy联系:
[email protected]
(出处:http://www.sheup.com)
上一页 [1] [2]