c++ - 了解模板和函数指针

标签 c++ templates function-pointers static-methods

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);
}

最佳答案

类的静态函数成员只是类命名空间中的常规函数​​:

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

在您的示例中,A::f1 的类型将是 void(A*)A::f2 的类型将是 void(A&)。值得注意的是,静态函数不需要调用实例。

或者,非静态成员函数确实需要调用一个实例。你必须使用 pointers to class members .在您的示例中,您将使用 &A::f1&A::f2 并且它们的类型将是 (void)A::*f1(A*) (void)A::*f2(A&) 分别。如果指向成员函数的指针被视为常规函数指针,将如何调用它们?他们需要一个对象实例来让 this 指针指向。

您可以使用 std::bind 将指向成员函数的指针转换为重载 () 运算符并表现得像函数(也称为仿函数)的对象:

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

但是,仿函数与函数指针的类型不同。我建议使用 std::functionfunctional 头文件中而不是函数指针,因为它们适用于仿函数。

(有关详细信息,请参阅 http://en.cppreference.com/w/cpp/language/pointer。)

关于c++ - 了解模板和函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47695701/

相关文章:

c++ - 具有不同原型(prototype)的函数指针 vector ,我可以构建一个吗?

c - 涉及函数指针和状态机的代码说明

c++ - 地址、reinterpret_cast 和多重继承

C++ 模板 - 在元组及其类型的容器上进行模板化

c++ - 在带有可变参数模板的基于模板的类中进行完善转发?

更改返回的可变参数函数指针

函数指针类型的c++模板调用

c++ - 在 std::function 原型(prototype)中使用 'this' 指针

iphone - 访问方法内部变量时 iPhone (C++) 上的 EXC_BAD_ACCESS

c++ - 带有模板的 CUDA 内核启动宏