开发者

Private inheritance using directive, overloads?

开发者 https://www.devze.com 2023-02-04 21:39 出处:网络
I\'m using private inheritance in a project, in the \"implemented in terms of\"-sense. The base class defines ope开发者_开发百科rator[], and this is the functionality I want to use. Thus, I have

I'm using private inheritance in a project, in the "implemented in terms of"-sense. The base class defines ope开发者_开发百科rator[], and this is the functionality I want to use. Thus, I have

class A : private B {
    using B::operator[];
    // ...
};

However, how can I control which version of the operator[] I get? In fact, I need more than one, both the const and non-const versions. Can this be accomplished?


My understanding is that your using should automatically bring in all the different overloads of the operator. Are there certain overloads you want to exclude from being brought into the child class? In that case it might be better to split the work into several differently named functions in the parent and only using the ones you need.


This does as expected:

class A
{
public:
  int operator[](int idx) { return 0; }
  int operator[](int idx) const { return 1; }
};

class B : public A
{
public:
  using A::operator[];

  void opa() { cout << operator[](1) << endl; }
  void opb() const { cout << operator[](1) << endl; }
};

int main(void)
{
  B b;
  b.opa();
  b.opb();

  const B d = B();
  cout << d[1] << endl; // should trigger the const version of operator[]
  return 0;
}

In another words, the appropriate const/non const versions are injected into B. NOTE: If the const version is not provided, then you will receive a compiler error (this works whether the inheritance is private or public).

0

精彩评论

暂无评论...
验证码 换一张
取 消