通过CRTP类继承的模板化派生类,访问基类成员对象
Templatized derived class inheriting through CRTP class, access to base class member object
如果我试图从继承层次结构另一端的模板类调用基类成员的成员函数,
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
本身的成员
这种情况不会发生在非模板的final类中(其中有很多已经在使用,都是通过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++:为什么无法在派生类中访问受保护的构造函数?
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 派生的 wxPanel 控件如何访问其中包含 wxDialog 中的数据?
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- C ++基础私有方法在将自身转换为派生类后可以访问吗?
- 按基类对象访问派生类资源时出错
- 使(虚拟)函数在大多数派生类中无法访问中间基类中可访问,定义良好?
- 从模板化父类中的派生内部类访问受保护的成员变量
- 如何从派生类访问基类中的重载运算符?
- 两个抽象类,派生自同一个基类.如何访问从一个抽象类到另一个抽象类的指针
- C++11: 如何访问派生类中的基类成员?
- 访问派生类的 QMetaObject
- 使用基类对象访问派生的仅类方法
- 如何在 c++ 中通过基类引用访问派生类的对象?
- 派生类无法访问基类的受保护成员
- 如何在 c++ 中使用多态性访问派生类字段?
- 为了访问方法,从基类动态转换为派生类
- C++继承从基类指针访问派生类中的非虚拟函数