收集不同类型的类,并在c++中调用它们的方法

collect different types of class and call their methods in c++

本文关键字:调用 方法 c++ 同类型 并在      更新时间:2023-10-16

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的编译器时,这才会起作用。