如何模拟方法模板的虚拟性 [英] How to simulate virtuality for method template

查看:125
本文介绍了如何模拟方法模板的虚拟性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类层次结构,我想引入一个方法模板,如果它是虚拟的。例如简单的层次结构:

I have a class hierarchy where I want to introduce a method template that would behave like if it was virtual. For example a simple hierarchy:

class A {
  virtual ~A() {}

  template<typename T>
  void method(T &t) {}
};

class B : public A {
  template<typename T>
  void method(T &t) {}
};

然后我创建对象B:

A *a = new B();

我知道我可以得到类型存储在 a typeid(a)。当我知道类型时,如何动态调用 B :: method ?我可能有一个像这样的条件:

I know I can get the type stored in a by typeid(a). How can I call the correct B::method dynamically when I know the type? I could probably have a condition like:

if(typeid(*a)==typeid(B))
    static_cast<B*>(a)->method(params);

但我想避免有这样的条件。我正在考虑创建一个 std :: map typeid 作为键,但我将作为一个值

But I would like to avoid having conditions like that. I was thinking about creating a std::map with typeid as a key, but what would I put as a value?

推荐答案

您可以使用Curiously Recurring Template Pattern
http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

You can use the "Curiously Recurring Template Pattern" http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

使用此模式,基类派生类类型作为模板参数,这意味着基类可以将自身强制转换为派生类型,以便在派生类中调用函数。这是一种编译时虚拟函数的实现,另外一个好处是不必进行虚拟函数调用。

Using this pattern, the base class takes the derived class type as a template parameter, meaning that the base class can cast itself to the derived type in order to call functions in the derived class. It's a sort of compile time implementation of virtual functions, with the added benefit of not having to do a virtual function call.

template<typename DERIVED_TYPE>
class A {
public:
    virtual ~A() {}

    template<typename T>
    void method(T &t) { static_cast<DERIVED_TYPE &>(*this).methodImpl<T>(t); }
};

class B : public A<B>
{
friend class A<B>;

public:
    virtual ~B() {}

private:
    template<typename T>
    void methodImpl(T &t) {}
};

它可以像这样使用...

It can then be used like this...

int one = 1;
A<B> *a = new B();
a->method(one);

这篇关于如何模拟方法模板的虚拟性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆