简体   繁体   English

C ++模板化容器扫描器

[英]c++ templated container scanner

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. 然后是A的各个子类,都实现了它们的良好doit方法。 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? 该序列是A子类的序列,例如list<A*> <A *>或vector ...该函数应在扫描迭代器时调用所有doit方法...如何执行此操作? 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*> ? 是否有可能使用list<A>而不是list<A*>

Why do you think you need the cast? 为什么您认为需要演员表? If it is a collection of A * you should just be able to say: 如果它是A *的集合,您应该可以说:

(*begin)->doIt();

You can use the std::foreach for that: 您可以使用std::foreach来实现:

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. std::mem_fun将创建一个对象,该对象为其operator()参数调用给定的成员函数。 The for_each will call this object for every element within v.begin() and v.end() . for_each将为v.begin()v.end()每个元素调用此对象。

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 ? 什么是“可序列化”类型?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM