通过基指针访问派生类中的模板化函数

时间:2012-11-10 00:57:28

标签: c++ templates inheritance

这是我的问题的抽象。

我想开发类似的东西。

class Base {
}

template<typename T>
class TypedBase : Base {

    f(const T& input);
}

现在我想通过基指针访问TypedBase类的“族”并调用f。

像这样的东西

Base* base_ptr;
if (condition) {
  base_ptr = new TypedBase<double>();
} else {
  base_ptr = new TypedBase<int>();
}

// Int and double are just examples to get the idea
// Then I Want to call

base_ptr->f(4);

这不会编译。

我尝试添加一个空的虚函数f()来希望vtable在运行时负责调用正确的f()与f(T&amp; input),但是再次没有像以下那样工作:

class Base {
   virtual f() = 0;
}

那你怎么做的?一般来说,我希望有一个指向通用TypedBase的指针,它允许我通过指向该族的通用指针调用f(...)。有什么想法吗?

当然,我可以这样做:

class Base {
    // Repeat for every typename
    virtual f(int& x) = 0;
    virtual f(double& x) = 0;
} 

然后每个TypedBase只会实现其中一个,因此我仍然可以在运行时获得类型安全,而无需在代码中进行动态检查。但是,如果我有N个函数要调用和M类型可以使用,那么我将不得不将M * N个抽象函数添加到Base类。有更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

你必须static_cast(如果你知道真实的类型)或dynamic_cast(如果你需要检查是否成功转换)指向右类的基指针。如果你知道你传递给方法的是什么,那么转换为接受该参数的类型应该不是问题。另外,转换应该在具有正确模板类型的模板方法中工作。

以下编译吗?

template <typename T>
void callF(Base *p, T input) {
  TypedBase<T> *tp = dynamic_cast<TypedBase<T>*>(p);
  if (tp) tp->f(input);
  // else throw exception or call some Base method or return error or...
}

或者不太安全,只需这样做:

static_cast<TypedBase<int>*>(base_ptr)->f(1);
相关问题