带有参数C++的void函数指针的矢量

Vector of void function pointers with parameters C++

本文关键字:指针 函数 void 参数 C++      更新时间:2023-10-16

我正在创建一个应用程序,该应用程序的类具有许多动画方法。我需要以随机的方式调用这些动画方法。所以,我的想法是创建一个void函数指针的向量,并遍历该向量。不过我无法编译它。我得到错误:"invalid use of void expression"

适用代码:

.h

std::vector<void(*)(int,float)> animationsVector;
void setAnimations();
void circleAnimation01(int circleGroup, float time);

.cpp

polygonCluster01::polygonCluster01()
{
    setAnimations();
}
void polygonCluster01::setAnimations()
{
    animationsVector.push_back(circleAnimation01(1,2.0)); //error is here
}
void polygonCluster01::circleAnimation01(int circleGroup, float animLength)
{
    //other code
}

我在这里关注了其他一些帖子,这些帖子表明我做得对,但它仍然无法编译,我不知道为什么。

polygonCluster01::circleAnimation01不是一个独立的函数,而是一个成员函数。因此,您需要一个成员函数指针来存储其地址。这是你要找的类型:

std::vector<void(polygonCluster01::*)(int,float)> animationsVector;
//               ^^^^^^^^^^^^^^^^^^

编辑:让我们完成这个答案。

当您为向量指定正确的类型时,它仍然不会编译。这是因为,正如crashmstr所说,函数指针和成员函数指针只是指向(成员)函数的指针。特别是,它们不能存储参数供以后使用,而您正试图这样做

因此,您实际需要的不仅仅是一个(成员)函数指针,而是可以包装函数和一些参数以便稍后调用它的东西。

好吧,C++11已经涵盖了你!看看std::function。这是一个类型擦除的容器,设计用于执行上面所写的操作。你可以这样使用它:

std::vector<std::function<void(polygonCluster01*)>> animationsVector;
...
animationsVector.push_back(std::bind(
    &polygonCluster01::circleAnimation01, // Grab the member function pointer
    std::placeholders::_1, // Don't give a caller for now
    1, 2.0 // Here are the arguments for the later call
));
...
animationsVector[0](this); // Call the function upon ourselves

您的向量包含函数指针,而不是您在其中调用的函数的结果。

animationsVector.push_back(circleAnimation01(1,2.0));

使用此替代

animationsVector.push_back(circleAnimation01);

您得到的invalid use of void expression是因为您试图存储circleAnimation01函数调用的结果,即void,而不是指向在接收到int和float时返回void的函数的指针。

此外,正如Quentin所说,你需要它们是函数,而不是成员函数,要么更改向量的签名,要么将这些成员更改为自由函数。