Class Templates and Virtual Functions

Given the code below, why does the compiler throw an error (saying that the method is calc()not a member Model2) when using an instance Sub<Model2>, if fn()declared virtual and works when fn()not virtual? What's happening?

class Model1
{
public:
    void calc(){std::cout<<"Model1 calc"<<std::endl;}
};
class Model2
{
public:
    void calc2(){std::cout<<"Model2 calc"<<std::endl;}
};
template<typename T>
class Super : public T
{
public:
    virtual void fn() // comment virtual for resolution
    { T::calc(); }
};
template<typename T>
class Sub : public Super<T>
{
public:
    void fn()
    { T::calc2(); }
};
int main()
{
    Super<Model1> bes;
    bes.fn();
    Sub<Model2> sts1;
    sts1.fn();
    return 0;
}
+4
source share
1 answer

virtual methods must be created in a template, while non-virtual methods do not.

Errors depending on the Tβ€œrequirement” occur at the time of creation. Non-virtual methods are created only by use or by an explicit instance.

, , Super<Model2>::fn ( Sub<Model2>::fn).
Super<Model2>::fn , , .

+2

Source: https://habr.com/ru/post/1541072/


All Articles