两阶段查找:我可以避免“代码膨胀”吗?

时间:2010-04-02 20:15:06

标签: c++ lookup using-directives phase

两阶段查询问题: 是否有更合成的方法来编写此代码,即避免所有这些using指令? 像using CBase<T>;这样的东西就是我想要的,但它不被接受。

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

在我的真实代码中有更多的成员变量/函数,我想知道是否有可能以某种方式编写更短的代码。
当然,使用this->c语法并不能解决问题...

感谢的!


gcc 4.1 MacOS X 10.6

2 个答案:

答案 0 :(得分:2)

我减少了测试用例,然后考虑了三个选项

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

选项1

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

选项2

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

选项3

// use your using declarations

答案 1 :(得分:0)

看起来大多数变量都没有参数化。 CBase是全部使用它们,还是只使用a?如果没有,请将它们移动到CDer

的新非模板库中

或者,将它们全部打包到POD结构中,然后using CBase<T>::m_ints;

高开销解决方案:非模板virtual基础。

不确定但值得一试:将CDer的定义嵌套在CBase内,然后将typedef嵌入到命名空间范围内。