我有一个C++模板类,它包含一个方法指针和一个类指针,谁有单个方法call,它调用类指针上的方法指针.
调用此模板Method< C >,C是类和方法指针的类.
我想创建一个std::vector这个模板的数组(),但我希望这个向量能够包含这个模板的不同类.我的最终目标是通过这个向量并调用call每个元素的方法,即使它们有不同的类.
你会怎么做?
你不能存储templateS IN vector,只有objects有types.并template成为type实例化的时候.
所以,你无法做到你想要的.
我建议你用function和bind.看一个例子:
struct A
{
void call()
{
std::cout << "hello";
}
};
int main()
{
std::vector <std::function<void()>> v;
v.push_back(std::bind(&A::call, A()));
for (auto it = v.begin(); it != v.end(); ++it) {
(*it)();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它完全是你想要的.