模板化派生类通过CRTP类继承,访问基类成员对象

发布于 2024-12-28 21:50:13 字数 963 浏览 1 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

同展鸳鸯锦 2025-01-04 21:50:13

你做错了:

 using basis::foo; //wrong way

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

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

因为 crtp<依据,选择choice 类的基类,foo 通过其成为 choice 的成员基类。所以有一个微妙的区别。

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

You're doing it wrong way:

 using basis::foo; //wrong way

What 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文