How to simulate virtuality for method template

后端 未结 5 1036
忘了有多久
忘了有多久 2021-01-19 14:08

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 {
  vi         


        
5条回答
  •  伪装坚强ぢ
    2021-01-19 14:53

    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
    class A {
    public:
        virtual ~A() {}
    
        template
        void method(T &t) { static_cast(*this).methodImpl(t); }
    };
    
    class B : public A
    {
    friend class A;
    
    public:
        virtual ~B() {}
    
    private:
        template
        void methodImpl(T &t) {}
    };
    

    It can then be used like this...

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

提交回复
热议问题