Can a class member function template be virtual?

前端 未结 13 1226
旧时难觅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:08

    The following code can be compiled and runs properly, using MinGW G++ 3.4.5 on Window 7:

    #include 
    #include 
    
    using namespace std;
    
    template 
    class A{
    public:
        virtual void func1(const T& p)
        {
            cout<<"A:"<
    class B
    : public A
    {
    public:
        virtual void func1(const T& p)
        {
            cout<<"A<--B:"< a;
        B b;
        B c;
    
        A* p = &a;
        p->func1("A a");
        p = dynamic_cast*>(&c);
        p->func1("B c");
        B* q = &b;
        q->func1(3);
    }
    

    and the output is:

    A:A a
    A<--B:B c
    A<--B:3
    

    And later I added a new class X:

    class X
    {
    public:
        template 
        virtual void func2(const T& p)
        {
            cout<<"C:"<

    When I tried to use class X in main() like this:

    X x;
    x.func2("X x");
    

    g++ report the following error:

    vtempl.cpp:34: error: invalid use of `virtual' in template declaration of `virtu
    al void X::func2(const T&)'
    

    So it is obvious that:

    • virtual member function can be used in a class template. It is easy for compiler to construct vtable
    • It is impossible to define a class template member function as virtual, as you can see, it hard to determine function signature and allocate vtable entries.

提交回复
热议问题