我正在尝试创建一个类/结构,它可以接受所有具有函数update()
的不同类型的结构/类。
我想得到update()
函数,然后把它作为一个指针放在一个向量中,然后再调用它,但是我把成员函数指针放到一个向量中时遇到了麻烦,但我把没有问题放到'无类'函数指向向量。
如何将成员函数指针放入向量?
这是我的代码
#include <vector>
#include <iostream>
#include <stdio.h>
using namespace std;
struct typeA
{
public:
int data = 0;
void update()
{
cout << "hello, my data is " << data << endl;
}
};
struct typeB
{
float data = 0;
void update()
{
cout << "hi, my data is " << data << endl;
}
};
class typeListTwo
{
typedef void(*updaterFunc)();
vector <updaterFunc> items;
public:
typeListTwo()
{
}
~typeListTwo()
{
items.~vector();
}
void addItem(updaterFunc newItem)
{
items.push_back(newItem); //This works
}
void doWork()
{
for (unsigned int funcIndex = 0; funcIndex < items.size(); funcIndex++)
{
items[funcIndex]();
}
}
};
class typeList
{
typedef void(*updaterFunc)();
vector <updaterFunc> items;
public:
typeList()
{
}
~typeList()
{
items.~vector();
}
template <class Item>
void addItem(Item newItem)
{
items.push_back(newItem.update); //But this does not?
//newItem.update(); //This also works by itself
}
void doWork()
{
for (unsigned int funcIndex = 0; funcIndex < items.size(); funcIndex++)
{
items[funcIndex]();
}
}
};
void aFunc()
{
cout << "123 hello" << endl;
}
void bFunc()
{
cout << "456 goodbye" << endl;
}
int main()
{
typeA aThing;
typeB bThing;
typeList listThings;
typeListTwo listThingsTwo;
aThing.data = 128;
bThing.data = -3.234;
listThings.addItem(aThing);
listThings.addItem(bThing);
listThings.doWork();
listThingsTwo.addItem(aFunc);
listThingsTwo.addItem(bFunc);
listThingsTwo.doWork();
return 0;
}
答案 0 :(得分:0)
要走的路是使用std::function
或使用interface:
class typeList
{
std::vector<std::function<void()>> items;
public:
template <class Item>
void addItem(Item& item)
{
// Care: life time of item should be bigger than this instance
items.push_back([&](){ item.update(); });
}
void doWork()
{
for (auto& f : items)
{
f();
}
}
};