带参数C ++的void函数指针向量

时间:2014-09-18 14:09:12

标签: c++

我正在创建一个具有多个动画方法的类的应用程序。我需要以随机的方式调用这些动画方法。所以,我的想法是创建一个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
}

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

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:0)

你的向量包含函数指针,而不是你在那里调用的函数的结果。

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

改为使用

animationsVector.push_back(circleAnimation01);

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

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