如果我试图从继承层次另一端的模板类中调用基类成员的成员函数,
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/