转载请注明原文链接。

原文链接:http://www.cnblogs.com/xianyunhe/archive/2011/11/27/2265148.html

 

指向一般函数的指针可实现对参数类型、参数顺序、返回值都一样的函数进行封装,指向类的成员函数的指针可实现对一个类中的参数类型、参数顺序、返回值都一样的函数进行封装。对于函数之前,前面已经进行了讨论,该文章的链接为:

http://www.cnblogs.com/xianyunhe/archive/2011/11/26/2264709.html

 

那么,如何能实现对不同类的成员函数进行统一调用呢?我们首先想到的应该会是函数模板和类模板。

下面就一个例子来说明如何实现对不同类的函数成员函数指针的调用。

 

#include <iostream.h>

class CA
{
public:

int Sum(int a, int b)
{
return a+b;
}
};

class CB
{
public:
float Sum(float a, float b)
{
return a+b;
}
};


template <typename ClassType, typename ParaType>
class CC
{
public:
/*函数指针类型模板*/
typedef ParaType (ClassType::*pClassFun)(ParaType, ParaType);

/*函数指针函数模块*/
ParaType Result(ClassType* pClassType, pClassFun fun, ParaType a, ParaType b)
{
return (pClassType->*fun)(a, b);
}

};


void main()
{
/*测试整型*/
CA ca;
CC<CA,int> cc;
int a = 3;
int b = 4;
cout<<"The sum of a and b is "<<cc.Result(&ca, CA::Sum, a, b)<<endl;

/*测试浮点型*/
CB cb;
CC<CB,float>fcc;
float fa = 3.3f;
float fb = 4.6f;
cout<<"The sum of fa and fb is "<<fcc.Result(&cb, CB::Sum, fa, fb)<<endl;
}

 

总结:

1、指针函数模板的使用需要结合类模板和函数模板。

2、类模板中的函数模板的定义必须位于头文件,或者和调用函数位于同一文件,且在调用函数的上方,否则会出现编译错误。

posted on 2011-11-27 17:16  闲云鹤  阅读(8567)  评论(4编辑  收藏  举报