如何公开私有基类的方法?

时间:2014-06-20 16:40:06

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

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

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
 };

1 个答案:

答案 0 :(得分:5)

using A::f1应该有效,但它会在A中公开所有名为f1的函数。如果你不想要这个,你需要为你想要公开的每个函数创建一个代理

模板的诀窍

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

只能用元程序完成,但它无论如何都行不通,因为你不能在函数上重载函数的返回类型,所以你不能选择正确的函数,除非你愿意写{{1}每次调用函数时都会。

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

但是,你可以去。如果你创建了具有所有可能结果的所有f3函数,编译器就不会知道要调用的函数,因为你不能使函数超载它的结果。

相关问题