c++ - 模板化派生类通过CRTP类继承,获取基类成员对象

标签 c++ templates inheritance member crtp

如果我试图从继承层次另一端的模板类中调用基类成员的成员函数,

class memberobj {public: void bar(){}};

class basis {public: memberobj foo;};

template<class Base, class Derived>
class crtp : public Base { /* ... */ };

template<class Option>
class choice : crtp< basis, choice<Option> > {
  using basis::foo;
 public:
  void test () {foo.bar();}
};

class someoption {};

int main() {
  choice<someoption> baz;
  baz.test();
  return 0;
}

我收到此错误消息:

g++-4.6 -o bin/crtptest crtptest.cpp
crtptest.cpp: In member function ‘void choice<Option>::test()’:
crtptest.cpp:12:21: error: ‘class basis’ has no member named ‘bar’
make: *** [bin/crtptest] Error 1

尽管 bar 显然是 basis 的成员,而不是 basis 本身的成员。
非模板最终类不会发生这种情况(其中一些已经在使用中,全部派生自 crtp 中间类;所以我不想对此进行任何更改),也不使用直接派生自 basis 的模板类。

这里有什么问题吗?

最佳答案

你做错了:

 using basis::foo; //wrong way

什么是 basis ?它不是 choice 的基类.你应该这样做:

typedef crtp< basis, choice<Option> > base;
using base::basis::foo;

因为 crtp< basis, choice<Option> >choice 的基础类,和 foo成为 choice 的成员通过它的基类。所以有细微的差别。

现在可以了:http://ideone.com/RPnyZ

关于c++ - 模板化派生类通过CRTP类继承,获取基类成员对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8977839/

相关文章:

c++ - 仅分析我需要使用 VS2010 的命名空间

c++ - 获取一个类的所有继承类

c++ - Unordered_map : Error in template arguments

c++ - 不同类型的运算符

c++ - 如何使派生类的成员只读?

c++ - 为什么编译器告诉我在 'if'和 'else if'语句中没有运算符与操作数类型匹配?

javascript - 主干模板嵌套在另一个模板中

c++ - 继承模板类并连接到信号

Java如何使方法参数接受子类类型和父类(super class)

python - Python 中的 BaseException 子类问题