【问题标题】:How to make part of the private base class's methods public? [closed]如何将私有基类的部分方法公开? [关闭]
【发布时间】:2014-06-20 16:40:05
【问题描述】:

例如,我有一个包含许多方法的基类

class A
{
public:
    void f1();
    int f2() const;
    float f3(double a, char b) const;
    ...
};

而一个类B是从A私有派生的。我想让A的一些方法是公开的,怎么办?

class B : private A
{
public:
    using A::f1; 
    using A::f2;

    template<class... Args>
    RETURN f3(Args&&... args) CONSTNESS  { return A::f3(args...); }
    // how to specify return and constness automatically

    ... 
};

我尝试了上述方法,但它们不起作用。模板方式需要自动指定return和constness。

问错了,在我的真实案例中,A是一个模板类

template<class T>
class A
{
public:
    void f1();
    int f2() const;
    float f3(double a, char b) const;
    ...
};

B 派生自 A

 template<class T>
 class B : public A
 {
 public:
     using A::f1; // wrong
     using A<T>::f1; // okay
 };

【问题讨论】:

  • using A::f1 应该可以工作。你用什么编译器?

标签: c++ templates inheritance c++11


【解决方案1】:

using A::f1 应该可以工作,但它会公开所有在 A 中称为 f1 的函数。如果您不希望这样做,则需要为要公开的每个函数创建一个代理

模板的诀窍

template<class... Args>
RETURN f3(Args&&... args) CONSTNESS  { return A::f3(args...); }

只能用元程序完成,但无论如何它都不起作用,因为你不能在它的返回类型上重载一个函数,所以你不能选择正确的函数,除非你愿意在每次调用时写f3&lt;float&gt;函数。

你不能“指定”返回值和常量,因为你没有指定任何东西。您创建所有可能的具有不同参数的 f3 函数,而那些在 A 中没有对应 f3 的函数在使用时将无法编译。

但这是你能做到的。如果你用所有可能的结果创建所有 f3 函数,编译器将不知道要调用哪一个,因为你不能在它的结果上重载函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2014-01-20
    • 2019-04-18
    相关资源
    最近更新 更多