一千萬個為什麽

搜索

如何將Base *指針視為Derived <T> *指針?

我想在 vector 中存儲指向 Base 類的指針,但是然後將它們用作函數參數,它們充當特定的類,請參見此處:

#include 
#include 

class Base {};

template
class Derived : public Base {};

void Foo(Derived* d) {
  std::cerr << "Processing int" << std::endl;
}

void Foo(Derived* d) {
  std::cerr << "Processing double" << std::endl;
}

int main() {
  std::vector vec;
  vec.push_back(new Derived());
  vec.push_back(new Derived());
  Foo(vec[0]);
  Foo(vec[1]);
  delete vec[0];
  delete vec[1];
  return 0;
}

這不編譯:

error: call of overloaded 'Foo(Base*&)' is ambiguous

有可能使它工作嗎?我需要根據int,double等類型不同地處理向量的元素。

最佳答案

你需要使用方法多態,因為它是動態的,而不是函數重載,這是靜態的(編譯時)。要在模板化類型上重載,您需要使用模板特化。

例:

#include 
#include 

class Base {
  public:
    virtual void Foo() {
      std::cerr << "Processing base" << std::endl;
    }
};

template
class Derived : public Base {};

template <>
class Derived  : public Base {
  public:
    void Foo() {
      std::cerr << "Processing int" << std::endl;
    }
};

template <>
class Derived  : public Base {
  public:
    void Foo() {
      std::cerr << "Processing double" << std::endl;
    }
};

int main() {
  std::vector vec;
  vec.push_back(new Derived());
  vec.push_back(new Derived());
  vec[0]->Foo();
  vec[1]->Foo();
  delete vec[0];
  delete vec[1];
  return 0;
}

轉載註明原文: 如何將Base *指針視為Derived <T> *指針?