收集不同类型的类,并在c++中调用它们的方法
collect different types of class and call their methods in c++
C++中有什么方法可以收集不同类型的类并调用它们的方法吗?,我想做的如下
template<namespace T>
class A
{
A method_A1(T a)
{
...
}
void method_A2(int aa)
{
...
}
...
};
class B
{
...
};
class C
{
...
};
class D
{
...
};
A<B> *b;
A<C> *c;
A<D> *d;
b -> method_A2(3);
c -> method_A2(5);
在这个代码对象b,c,d中,它们是完全不同的对象,对吧?不相关。但我想用数组绑定它们,所以…
z[0] = b;
z[1] = c;
z[2] = d;
像这样。我找到了一些解决方案,但这些解决方案仅用于收集不同类型的数据。(对继承的对象使用void*数组或向量)我也想访问它们的方法。
z[0] -> method_A2(3);
z[1] -> method_A3(5);
像这样。在这种情况下,我该怎么办?
提前谢谢。
typedef boost::variant<A<B>, A<C>, A<D>> AVariant;
std::array<AVariant, 3> z;
z[0] = *b;
z[1] = *c;
z[2] = *d;
然后,如果需要,您可以检查每个元素的类型,或者使用boost::static_visitor
"访问"它们,如下所示:http://www.boost.org/doc/libs/release/doc/html/variant.html
为什么不使用遗传和多态性。我贴出了一个例子,说明什么可以解决你的问题。参见main
功能:
#include <iostream>
class weapon {
public:
int fireRate;
int bulletDamage;
int range;
int activeBullet;
public:
virtual void fire(void) {std::cout << "machine " << 'n';}
virtual ~weapon() {std::cout << "destructor is virtual" << 'n';}
};
class machineGun: public weapon {
public:
void fire(void) {std::cout << "machine gun firing" << 'n';}
~machineGun(void) { std::cout << "machine gun destroyed" << 'n';}
};
class flamer: public weapon {
public:
void fire(void) {std::cout << "flamer firing" << 'n';}
~flamer(void) {std::cout << "flamer destroyed" << 'n';}
};
int main(void)
{
const int count = 2;
weapon *weapons[count];
machineGun *a = new machineGun();
flamer *b = new flamer();
weapons[0] = a;
weapons[1] = b;
weapons[0]->fire();
weapons[1]->fire();
delete a;
delete b;
}
如果不想更改类的层次结构,可以尝试使用一个可调用对象数组。类似于:
#include <iostream>
#include <functional>
#include <array>
class A
{
public:
void Foo(int a)
{
std::cout << "Foo " << a << std::endl;
}
};
class B
{
public:
void Bar(int a)
{
std::cout << "Bar " << a << std::endl;
}
};
int main()
{
using namespace std::placeholders;
A a;
B b;
auto a_func = std::bind(&A::Foo, a, _1);
auto b_func = std::bind(&B::Bar, b, _1);
std::array<std::function<void(int)>, 2> arr = {
std::bind(&A::Foo, a, _1),
std::bind(&B::Bar, b, _1)
};
arr[0](1);
arr[1](2);
return 0;
}
顺便说一句,只有当您使用完全支持C++11的编译器时,这才会起作用。
相关文章:
- 在c++中多次调用方法
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 接收字符串并使用它来调用方法C++
- 使用 gmock c++ 在真实对象上调用方法
- 不带预处理器的调用方法/文件的文件名/行号
- JNI从Android调用C++方法
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何使用接口指针调用方法,该指针是其具体类的一部分,而不是接口的一部分
- 从内部类中的方法从包含类调用方法
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 为什么派生类的实例从基类调用方法?
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- C++当您取消引用指向类对象的指针,然后将其作为引用返回时,是否可以对此引用调用方法
- 通过模板函数对未知类型调用方法
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 创建一个C++DLL以从C#DLL调用方法
- 如何从qt中的类中调用方法
- 如何在不迭代的情况下对数组中的每个元素调用方法
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- C ++:如何在不创建对象的情况下在主函数中调用方法