Can a class member function template be virtual?

前端 未结 13 1124
旧时难觅i
旧时难觅i 2020-11-22 03:29

I have heard that C++ class member function templates can\'t be virtual. Is this true?

If they can be virtual, what is an example of a scenario in which one would

13条回答
  •  轮回少年
    2020-11-22 04:17

    While an older question that has been answered by many I believe a succinct method, not so different from the others posted, is to use a minor macro to help ease the duplication of class declarations.

    // abstract.h
    
    // Simply define the types that each concrete class will use
    #define IMPL_RENDER() \
        void render(int a, char *b) override { render_internal(a, b); }   \
        void render(int a, short *b) override { render_internal(a, b); } \
        // ...
    
    class Renderable
    {
    public:
        // Then, once for each on the abstract
        virtual void render(int a, char *a) = 0;
        virtual void render(int a, short *b) = 0;
        // ...
    };
    

    So now, to implement our subclass:

    class Box : public Renderable
    {
    public:
        IMPL_RENDER() // Builds the functions we want
    
    private:
        template
        void render_internal(int a, T *b); // One spot for our logic
    };
    

    The benefit here is that, when adding a newly supported type, it can all be done from the abstract header and forego possibly rectifying it in multiple source/header files.

提交回复
热议问题