代码之家  ›  专栏  ›  技术社区  ›  sharvey

重写模板类函数

  •  2
  • sharvey  · 技术社区  · 16 年前

    我正在尝试为类模板创建某种回调。代码如下:

    template <typename t>
    class Foo {
        void add(T *t) {
            prinf('do some template stuff');
            on_added(t);
        }
        void on_added(T *t) { }
    }
    
    struct aaa {}
    
    class Bar : Foo<aaa> {
        void on_added(aaa *object) {
            printf("on added called on Bar");
        }
    }
    

    永远不会调用on-added函数on-bar。添加模板子类可以选择性重写的回调的最佳方法是什么?谢谢

    4 回复  |  直到 16 年前
        1
  •  4
  •   Will A    16 年前

    使用“虚拟”…

    template <typename t>
    class Foo {
        void add(T *t) {
            prinf('do some template stuff');
            on_added(t);
        }
        virtual void on_added(T *t) { }
    }
    
    struct aaa {}
    
    class Bar : Foo<aaa> {
        void on_added(aaa *object) {
            printf("on added called on Bar");
        }
    }
    
        2
  •  2
  •   Jesse Collins    16 年前

    您在foo中添加的函数需要是虚拟的。

        3
  •  0
  •   sth    16 年前

    你必须完成这个功能 virtual 如果希望基类中的调用使用派生类中的实现:

    template <typename t>
    class Foo {
        ...
        virtual void on_added(T *t) { }
    };
    

    请注意,这对模板不是特别的,但适用于所有类。

        4
  •  0
  •   Gangadhar    16 年前

    其他人都已经回答了这个问题。我想补充一点,添加虚拟函数会破坏类的向后兼容性。因此,如果这是一个您控制的类,并且没有其他依赖类,那么是的,您可以继续并转换 on_added 如果不是,则需要确保相关模块也已重建。