Generic base class with multiple template specialized derived classes

前端 未结 4 998
梦如初夏
梦如初夏 2021-02-09 02:58

I have a finite amount of classes with the nearly-same implementation, the only different being the underlying type of data they manipulate:

class IntContainer
{         


        
4条回答
  •  梦如初夏
    2021-02-09 03:32

    How about making base template too? Of course there is no way you can do something like

    std::vector v;
    v.push_back(intf);
    v.push_back(boolf);
    

    but the rest you can achieve with something simple as

    template
    class Base
    {
    public:
        virtual void setData(T data) = 0;
        virtual T getData() = 0;
    };
    
    // Modify GenericContainer's definition like so
    template
    class GenericContainer : Base { 
        T d;
        public:
        virtual void setData(T data) {d = data;}
        virtual T getData() { return d; }
    };
    

    You can use it in any way as long as types match.

    IntContainer intc = IntContainer();
    intc.setData(42);
    std::cout << intc.getData() << std::endl;
    
    BoolContainer boolc = BoolContainer();
    boolc.setData(true);
    std::cout << boolc.getData() << std::endl;
    
    std::vector v;
    v.push_back(intc);
    // v.push_back(boolc); No can't do.
    

提交回复
热议问题