如果我尝试从继承层次结构另一端的模板类调用基类成员的成员函数,
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 。
这有什么不对?
If I try to call a member function of a member of the base class from a template class on the other end of the inheritance hierarchy,
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; }I get this error message:
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 1though bar is obviously a member of a member of basis, not of basis itself.This does not happen with non-template final classes (of which a number are already in use, all deriving through the crtp intermediate class; so I wouldn't want to change anything about that), nor with a template class that directly derives from basis.
What's wrong here?
最满意答案
你这样做错了:
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
You're doing it wrong way:
using basis::foo; //wrong wayWhat is basis? It is not the base class of choice. You should be doing this instead:
typedef crtp< basis, choice<Option> > base; using base::basis::foo;Because crtp< basis, choice<Option> > is the base of choice class, and foo becomes a member of choice through its base class. So there is a subtle difference.
Now it works : http://ideone.com/RPnyZ
更多推荐
发布评论