在C ++中从子类调用重载的父方法

时间:2019-03-19 14:25:17

标签: c++ templates inheritance crtp overload-resolution

我试图了解是否可以从子类中调用父级的函数成员。

基本上我有以下代码:

struct Parent
   {
   template<class... Args>
   void doFoo(Args&&... args)
     {
     std::cout << "parent doFoo";
     }

   template<class... Args>
   void foo(Args&&... args)
     {
     doFoo(args...);
     }
   };

 struct Child : Parent
   {
     template<class... Args>
     void doFoo(Args&&... args)
       {
       std::cout << "child doFoo";
       }
   };

   Child c;
   c.foo(); // This should invoke Child::doFoo()

是否有一种简单的方法来获取“ child doFoo”作为输出而不引入开销?

1 个答案:

答案 0 :(得分:0)

I don't know if it's an option but if you can afford to template the class instead of the method, you're allowed to make "doFoo" virtual and then it works as you expect.

#include <iostream>

template <typename ... Args>
struct Parent
   {
   virtual void doFoo(Args&&... args)
     {
     std::cout << "parent doFoo";
     }

   void foo(Args&&... args)
     {
     doFoo(args...);
     }
   };

template <typename ... Args>
 struct Child : Parent <Args...>
   {
     void doFoo(Args&&... args) override
       {
       std::cout << "child doFoo";
       }
   };

int main()
{
   Child<> c;
   c.foo(); // This should invoke Child::doFoo()
}