Class member function pointer and mem_fun adapter usage

Source: Internet
Author: User

Let's take a look at the simplest function:

void foo(int a){    cout << a << endl;}

Its function pointer type is

void (*)(int);

We can use this method as follows:

void (*pFunc)(int) = &foo;pFunc(123);

This is the basic usage of function pointers.

 

Class member functions

 

So what are the differences between function pointers for class member functions?

Observe the following classes:

class Foo{public:    //void (Foo::*)(int)    void foo(int a)    {        cout << a << endl;    }    //void (*)(int)    static void bar(int a)    {        cout << a << endl;    }};

We try to use:

void (*pFunc)(int) = &Foo::foo;

Compilation error:

Error: cannot convert 'void (FOO: *) (INT) 'to 'void (*) (INT)' in Initialization

From the above compilation error, we can know that the foo function pointer type is definitely not the expected void (*) (INT), but void (FOO: *) (INT ).

The reason is very simple. The class member function contains an implicit parameter this, So Foo actually has two parameters: Foo * and Int.

Then we try to use the void (FOO: *) (INT) type, as follows:

void (Foo::*pFunc2)(int) = &Foo::foo;

So how can we call it? We use the following two methods:

Foo f;(f.*pFunc2)(45678);

And

Foo *pf = &f;(pf->*pFunc2)(7865);

In this case, the usage is correct.

 

So what are the characteristics of the bar function as a static function?

void (*pFunc)(int) = &Foo::bar; pFunc(123);

We found that the pointer types of static and free functions are the same.

 

Since Foo contains an implicit parameter, can it be converted? We use mem_fun in STL, which is a function adapter.

Foo f;//void (Foo::*)(int) -> void (*)(Foo*, int)(mem_fun(&Foo::foo))(&f, 123);

We can see that mem_func serves as a conversion function, converting the void (FOO: *) (INT) type member function pointer to void (*) (FOO *, INT ), the latter is a pointer of the free function type and can be freely called.

 

Complete.

Class member function pointer and mem_fun adapter usage

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.