如果我有:如何循环异构类的实例来调用具有相同名称和参数的方法?
class A {
void foo();
};
class B {
void foo();
};
有没有办法来收集A
类型和B
的情况下,对他们的循环调用foo()
方法?例如使用一些宏或指针和一些特殊的数据类型?或者收集函数指针?
下面的伪代码可能会给出我的意思。
int main() {
A a;
B b;
hypothetical_container_t hypothetical_container;
hypothetical_container.push_back(a);
hypothetical_container.push_back(b);
[...]//Do stuff with a, do other stuff with b
for (hypothetical_container_t::iterator ii = hypothetical_container.begin(); ii != hypothetical_container.end(); ++ii) {
ii->foo();
}
}
用例是具有一串boost::shared_ptr
变量具有不同类型T的并调用所有这些.reset()
。 (我知道在这个例子中调用重置将不是必需的)。
boost :: variant? – user1937198
也许尝试functor? – Jiang
编译时已知类型吗?如果是这样,你可以使用一个元组作为容器,并迭代一个可变模板。如果不是,则需要在公共基类中使用虚函数。 –