c++模板化集装箱扫描仪

发布于 2024-08-14 12:09:35 字数 594 浏览 2 评论 0原文

这是今天的困境:

假设我有

class A{
  public:
   virtual void doit() = 0;
}

A 的各个子类,都实现了它们好的 doit 方法。现在假设我想编写一个需要两个迭代器的函数(一个位于序列的开头,另一个位于序列的末尾)。该序列是 A 子类的序列,例如 list 或向量...该函数应该在扫描迭代器时调用所有 doit 方法...如何做到这一点?我想过:

template<typename Iterator> void doList(Iterator &begin, Iterator &end) {
    for (; begin != end; begin++) {
        A *elem = (serializable*) *begin;
        elem.doIt();
    }
}

但是给出了奇怪的错误...您有更好的想法或具体信息吗?是否可以使用 list 代替 list

here's today's dilemma:

suppose I've

class A{
  public:
   virtual void doit() = 0;
}

then various subclasses of A, all implementing their good doit method. Now suppose I want to write a function that takes two iterators (one at the beginning of a sequence, the other at the end). The sequence is a sequence of A subclasses like say list<A*> or vector... The function should call all the doit methods while scanning the iterators... How to do this? I've thought of:

template<typename Iterator> void doList(Iterator &begin, Iterator &end) {
    for (; begin != end; begin++) {
        A *elem = (serializable*) *begin;
        elem.doIt();
    }
}

but gives weird errors... do you have better ideas or specific information? Is it possible to use list<A> instead of list<A*>?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

岁月如刀 2024-08-21 12:09:35

您可以使用 std::foreach 来实现:

std::for_each( v.begin(), v.end(), std::mem_fun( &A::doIt ) );

std::mem_fun 将创建一个为其 operator() 调用给定成员函数的对象代码> 参数。 for_each 将为 v.begin()v.end() 中的每个元素调用此对象。

You can use the std::foreach for that:

std::for_each( v.begin(), v.end(), std::mem_fun( &A::doIt ) );

The std::mem_fun will create an object that calls the given member function for it's operator() argument. The for_each will call this object for every element within v.begin() and v.end().

魄砕の薆 2024-08-21 12:09:35

你认为为什么需要演员阵容?如果它是 A * 的集合,你应该可以说:

(*begin)->doIt();

Why do you think you need the cast? If it is a collection of A * you should just be able to say:

(*begin)->doIt();
合约呢 2024-08-21 12:09:35

您应该提供错误消息以获得更好的答案。

在您的代码中,首先想到的是使用

elem->doIt();

什么是“可序列化”类型?

You should provide error messages to get better answers.

In your code, the first thing that comes to mind is to use

elem->doIt();

What is the "serializable" type ?

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