指向抽象类

时间:2017-03-05 03:23:49

标签: c++ oop inheritance overloading c++98

我在C ++中遇到函数重载问题。

我有一个类层次结构,其中许多类继承自抽象基类,如下所示:

struct Animal {
  virtual void make_noise() = 0;
};

struct Dog : Animal {
  void make_noise() { std::cout << "bark\n"; }
};

struct Cat : Animal {
  void make_noise() { std::cout << "meow\n"; }
};

struct Lion : Cat {
  void make_noise() { std::cout << "roar\n"; }
};

我想要一个具有三种不同实现的函数,具体取决于参数的类型:

  • 指向Animal的子类的指针:Dog *Lion *等。
  • 一个指向Animal子类指针的向量:std::vector<Animal *>std::vector<Lion *>等。
  • 每个其他类型一个,即使是非指针类型:char *std::stringint等。

这是我的尝试:

void f(Animal *x) {
  x->make_noise();
}

void f(std::vector<Animal *> x) {
  std::cout << "vector\n";
}

template<class T>
void f(T a) {
  std::cout << a << "\n";
}

int main() {
  f(new Lion);
  std::vector<Animal *> x;
  f(x);
  f(2);
  return 0;
}

这是以上程序打印的内容:

0x7febb8d00000
vector
2

这就是我想要打印的内容:

roar
vector
2

此外,如果我尝试传递std::vector<Lion *>而不是std::vector<Animal *>,它会选择最后一个实现而不是第二个实现,并生成编译器错误。

如何在C ++ 98中解决此问题?

1 个答案:

答案 0 :(得分:1)

一种方法是使用模板特化并在f的调用中指定模板参数类型,如下所示:

template<class T>
void f(T a) {
  std::cout << a << "\n";
}

template<>
void f(Animal *x) {
  x->make_noise();
}

template<>
void f(std::vector<Animal *> x) {
  std::cout << "vector\n";
}


int main() {
  f<Animal *>(new Lion); // specify template param
  std::vector<Animal *> x;
  f(x);
  f(2);
  return 0;
}