C++ Logo

STD-DISCUSSION

Advanced search

Subject: Templatized virtual functions
From: Ritwik Das (ritwik.sami1990_at_[hidden])
Date: 2019-04-20 14:17:36


Hello,
I am almost sure this has come up before so I am looking for reasons why
this will not work or why this proposal has not been accepted by the
standard committee.

The following proposal does not change the way virtual functions work but
only helps in writing them in a more easier and concise manner by allowing
composability with template args.

*Current approach:*

class Base
{
      virtual int func_int() = 0;
      virtual int func_float() = 0;
};

class Child
{
      virtual int func_int() { return 1; }
      virtual int func_float() { return 0; };
};

void main()
{
      Base* p = new Child();
      int i = p->func_int();
      int j = p->func_float();
      delete p;
}

*Proposal:*

class Base
{
      template<typename T>
      virtual int func() = 0;
};

class Child
{
      template<typename T>
      virtual int func()
      {
            if (std::is_same_v<T, int>) return 0;
            return 1;
       }
};

void main()
{
      Base* p = new Child();
      int i = p->func<int>(); // Internally the compiler can create
named functions like func_int()
      int j = p->func<float>();
      delete p;
}

-- 
Ritwik Das



STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups