How to achieve “virtual template function” in C++

后端 未结 9 1651
囚心锁ツ
囚心锁ツ 2020-11-28 03:20

first off: I have read and I know now that a virtual template member function is not (yet?) possible in C++. A workaround would be to make the class a template and then use

9条回答
  •  清酒与你
    2020-11-28 03:50

    You can create a template class with virtual function, and implement the function in the derived class without using template in the follwing way:

    a.h:
    
    template 
    class A
    {
    public:
        A() { qDebug() << "a"; }
    
        virtual A* Func(T _template) { return new A;}
    };
    
    
    b.h:
    
    class B : public A
    {
    public:
        B();
        virtual A* Func(int _template) { return new B;}
    };
    
    
    and the function CTOR and call 
    
      A* a1=new B;
        int x=1;
        a1->Func(x);
    

    unfortunately i havn't found a way to create a virtual function with template parameters without declaring the class as a template and it template type on the dervied class

提交回复
热议问题