Home Understanding about templates and function pointer
Reply: 1

Understanding about templates and function pointer

Prakash
1#
Prakash Published in 2017-12-07 12:59:22Z

I would like to know Why have to make fun1() as static member function? function pointer in template? in below piece of code.

#include<iostream>
using namespace std;
class A
{
    int temp;
    public:
    A():temp(1){}
    template<class T, void (*fn)(T* )>
    static void create(T *ptr)
    {
        cout <<"create fn"<<endl;
        //fun1(ptr);
    }
    static void fun1(A* tp) 
    {
         cout<<"func temp"<<endl;
    }
    static void fun2(A& ob)
    {
        cout<<"fun2 start"<<endl;
        A::create<A,&A::fun1>(&ob);
        cout<<"fun2 end"<<endl;
    }
};
int main()
{
    A ob,ob1;
    ob.fun2(ob1);
}
The Aspiring Hacker
2#
The Aspiring Hacker Reply to 2017-12-07 23:03:30Z

A static function member of a class is simply a regular function in the class's namespace:

Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program.

cppreference.com

In your example, the type of A::f1 would be void(A*) and the type of A::f2 would be void(A&). Notably, static functions do not need an instance to be called.

Alternatively, non-static member functions do require an instance to be called. You would have to use pointers to class members. In your example, you would use &A::f1 and &A::f2 and their types would be (void)A::*f1(A*) and (void)A::*f2(A&) respectively. If pointers to member functions were treated as regular function pointers, how would they be called? They would need an object instance for the this pointer to point to.

You can convert a pointer to a member function to an object that overloads the () operator and behaves like a function (AKA a functor) using std::bind:

A a;
std::bind(&A::f1, &a); // &a is the value of this

However, functors do not have the same type as function pointers. I recommend using std::function in the functional header file instead of function pointers because they accommodate for functors.

(See http://en.cppreference.com/w/cpp/language/pointer for more information.)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.260002 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO