模板化派生类通过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
中间派生class; 所以我不想对此进行任何更改),也不想使用直接从 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 1
though 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你做错了:
什么是基础?它不是
choice
的基类。你应该这样做:因为
crtp<依据,选择
是choice
类的基类,foo
通过其成为choice
的成员基类。所以有一个微妙的区别。现在它可以工作了:http://ideone.com/RPnyZ
You're doing it wrong way:
What is
basis
? It is not the base class ofchoice
. You should be doing this instead:Because
crtp< basis, choice<Option> >
is the base ofchoice
class, andfoo
becomes a member ofchoice
through its base class. So there is a subtle difference.Now it works : http://ideone.com/RPnyZ