简体   繁体   中英

Two-phase lookup: can I avoid “code bloat”?

Two-phase lookup question: Is there a more synthetic way to write this code, ie avoiding all those using directives? Something like using CBase<T>; is what I would like, but it is not accepted.

#include <iostream>

template <typename T>
class CBase
{
protected:
    int a, b, c, d;   // many more...

public:
    CBase() {
        a = 123; c = 0;
    }
};


template <typename T>
class CDer : public CBase<T>
{
//  using CBase<T>;     // error, but this is what I would like
    using CBase<T>::a;
    using CBase<T>::b;
    //...

public:
    CDer() {
        std::cout << a << this->c;
    }
};


int main()
{
    CDer<int> cd;
}

In my real code there are many more member variables/functions, and I was wondering if it is possible to write shorter code in some way.
Of course, using the this->c syntax does not solve the problem...

Thank's!


gcc 4.1 MacOS X 10.6

I reduced the testcase and then consider three options

template<typename T> struct Base { int a; };

Option 1

template<typename T> struct Der : Base<T> {
  void f() { 
    int &ra = Der::a;
    // now use ra
  }
}

Option 2

template<typename T> struct Der : Base<T> {
  void f() { 
    // use this->a instead
    // or Der::a
  }
}

Option 3

// use your using declarations

It doesn't look like most of those variables are parameterized. Does CBase use them all, or just a ? If not, move them into a new non-template base of CDer .

Or, pack them all into a POD struct and then using CBase<T>::m_ints; .

High overhead solution: non-templated virtual base.

Not sure but worth a try: nest the definition of CDer inside CBase and then typedef it into namespace scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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