简体   繁体   English

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

[英]Calling an overloaded parent's method from a child class in C++

I'm trying to understand if is possible to call a parent's function member from a child class.我试图了解是否可以从子类调用父类的函数成员。

Basically I have the following code:基本上我有以下代码:

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()

Is there a simple way to obtain "child doFoo" as output without introducing overhead?有没有一种简单的方法可以在不引入开销的情况下获得“child doFoo”作为输出?

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.我不知道这是否是一个选项,但是如果您负担得起为类而不是方法模板化,则可以将“doFoo”设为虚拟,然后它会按您的预期工作。

#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()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM