Function pointer Template

Source: Internet
Author: User

Pointers to common functions can encapsulate functions with the same parameter type, parameter sequence, and return values, the pointer to a member function of a class can encapsulate functions with the same parameter type, Parameter order, and return value in a class. As discussed earlier, the link to this article is: http://www.bkjia.com/kf/201111/112430.html
Then, how can we call member functions of different classes in a unified manner? We should first think of function templates and class templates.
The following example shows how to call function pointers of function members of different classes.
 
# 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:
/* Function pointer type template */
Typedef ParaType (ClassType: * pClassFun) (ParaType, ParaType );

/* Function pointer function module */
ParaType Result (ClassType * pClassType, pClassFun fun, ParaType a, ParaType B)
{
Return (pClassType-> * fun) (a, B );
}

};


Void main ()
{
/* Test Integer type */
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;

/* Test floating point */
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;
}
 
Summary:
1. The use of pointer function templates must be combined with class templates and function templates.
2. The function template definition in the class template must be located in the header file, or be located in the same file as the called function and above the called function. Otherwise, a compilation error occurs.

From: http://www.cnblogs.com/xianyunhe/archive/2011/11/27/2265148.html
 
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.