gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:39:53 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com