开发者

Two-phase lookup: can I avoid "code bloat"?

开发者 https://www.devze.com 2022-12-25 06:15 出处:网络
Two-phase lookup question: Is there a more synthetic way to write this code, i.e. avoiding all those using directives?

Two-phase lookup question: Is there a more synthetic way to write this code, i.e. 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 << thi开发者_如何学JAVAs->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.

0

精彩评论

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

关注公众号