如何使父类的模板方法从子类中可见? [英] How to make a parent's template method visible from a child class?

查看:150
本文介绍了如何使父类的模板方法从子类中可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是示例代码:

#include <memory>

class A {
  public:
    template <class T> void f(std::unique_ptr<T>, int) {}

  private:
    virtual void f(int) = 0;
};

class B: public A {
  public:
    using A::f;

  private:
    virtual void f(int) override {}
};

int main() {
  std::unique_ptr<float> a;
  B* b = new B;
  b->f(std::move(a), 1);

  return 0;
}



当我用clang ++编译它时会出现错误:

When I compile it with clang++, I get an error:

'f' is a private member of 'A'
using A::f;
         ^

如何使模板方法 f(std: :unique_ptr< T>,int)可从 B类吗?

How to make the template method f(std::unique_ptr<T>, int) visible from class B?

注意:如果虚拟方法 A :: f(int)被移动到公共部分

Note: if the virtual method A::f(int) is moved to a public section - everything works fine.

推荐答案

通过从完全不相关的私有虚拟 f

By giving it distinct name from the completely unrelated private virtual f.

拥有一个重载函数,其中不同的重载具有不同的访问控制级别既不工作也没有意义。如果函数实际上做了相同的事情(或者给定参数的可比性),那么你应该使用相同的名称,但是将它们设为公共的和私有的没有意义。

Having an overloaded function where different overloads have different access control level neither works nor makes sense. You should only use the same name if the functions actually do the same (or comparable given the arguments) thing, but than it does not make sense to make one public and one private.

如果您有私人虚拟的公开包装(这是常见的,请参阅例如 std :: basic_streambuf ),只需向其中一个添加合适的前缀/后缀( std :: basic_streambuf 在公开使用 pub 通常更有意义的是添加 priv impl _ 到私人虚拟。

If you have a public wrapper over private virtual (which is common, see e.g. std::basic_streambuf), just add suitable prefix/suffix to one of them (std::basic_streambuf uses pub on the public, but it usually makes more sense to add priv, impl or _ to the private virtual.

这篇关于如何使父类的模板方法从子类中可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆