通过自定义模板化迭代器调整非迭代容器以进行迭代

DAl*_*dge 6 c++ templates

我有一些类,由于各种原因超出了本讨论的范围,我无法修改(省略了不相关的实现细节):

class Foo { /* ... irrelevant public interface ... */ };

class Bar {
  public:
    Foo& get_foo(size_t index) { /* whatever */ }
    size_t size_foo() { /* whatever */ }
};
Run Code Online (Sandbox Code Playgroud)

(我正在处理许多类似的'Foo'和'Bar'类,它是从其他地方生成的代码和我不想要子类的东西等等)

[编辑:澄清 - 虽然有许多类似的'Foo'和'Bar'类,但保证每个"外部"类都有getter和size方法.对于每个"外部",只有getter方法名称和返回类型会有所不同,具体取决于它所包含的"内部"类型.

所以,如果我有包含Quux实例的Baz,那么会有Quux&Baz :: get_quux(size_t index)和size_t Baz :: size_quux().]

鉴于Bar类的设计,你不能轻易地在STL算法中使用它(例如for_each,find_if等),并且必须做必要的循环而不是采用函数式方法(我更喜欢后者的原因也不在这个讨论):

Bar b;
size_t numFoo = b.size_foo();
for (int fooIdx = 0; fooIdx < numFoo; ++fooIdx) {
  Foo& f = b.get_foo(fooIdx);
  /* ... do stuff with 'f' ... */
}
Run Code Online (Sandbox Code Playgroud)

所以...我从来没有创建过自定义迭代器,在阅读了关于iterator_traits之类的各种问题/答案之后,我想出了这个(目前已经半生不熟的)"解决方案":

首先,自定义迭代器机制(注意:'function'和'bind'的所有用法都来自MSVC9中的std :: tr1):

// Iterator mechanism...
template <typename TOuter, typename TInner>
class ContainerIterator : public std::iterator<std::input_iterator_tag, TInner> {
  public:
    typedef function<TInner& (size_t)> func_type;

    ContainerIterator(const ContainerIterator& other) : mFunc(other.mFunc), mIndex(other.mIndex) {}

    ContainerIterator& operator++() { ++mIndex; return *this; }

    bool operator==(const ContainerIterator& other) {
      return ((mFunc.target<TOuter>() == other.mFunc.target<TOuter>()) && (mIndex == other.mIndex));
    }

    bool operator!=(const ContainerIterator& other) { return !(*this == other); }

    TInner& operator*() { return mFunc(mIndex); }

  private:
    template<typename TOuter, typename TInner>
    friend class ContainerProxy;

    ContainerIterator(func_type func, size_t index = 0) : mFunc(func), mIndex(index) {}

    function<TInner& (size_t)> mFunc;
    size_t mIndex;
};
Run Code Online (Sandbox Code Playgroud)

接下来,我获得表示内部容器的开始和结束的有效迭代器的机制:

// Proxy(?) to the outer class instance, providing a way to get begin() and end()
// iterators to the inner contained instances...
template <typename TOuter, typename TInner>
class ContainerProxy {
  public:
    typedef function<TInner& (size_t)> access_func_type;
    typedef function<size_t ()> size_func_type;

    typedef ContainerIterator<TOuter, TInner> iter_type;

    ContainerProxy(access_func_type accessFunc, size_func_type sizeFunc) : mAccessFunc(accessFunc), mSizeFunc(sizeFunc) {}

    iter_type begin() const {
      size_t numItems = mSizeFunc();
      if (0 == numItems) return end();
      else return ContainerIterator<TOuter, TInner>(mAccessFunc, 0);
    }
    iter_type end() const {
      size_t numItems = mSizeFunc();
      return ContainerIterator<TOuter, TInner>(mAccessFunc, numItems);
    }

  private:
    access_func_type mAccessFunc;
    size_func_type mSizeFunc;
};
Run Code Online (Sandbox Code Playgroud)

我可以通过以下方式使用这些类:

// Sample function object for taking action on an LMX inner class instance yielded
// by iteration...
template <typename TInner>
class SomeTInnerFunctor {
  public:
    void operator()(const TInner& inner) {
      /* ... whatever ... */
    }
};

// Example of iterating over an outer class instance's inner container...
Bar b; /* assume populated which contained items ... */
ContainerProxy<Bar, Foo> bProxy(
  bind(&Bar::get_foo, b, _1),
  bind(&Bar::size_foo, b));
for_each(bProxy.begin(), bProxy.end(), SomeTInnerFunctor<Foo>());
Run Code Online (Sandbox Code Playgroud)

根据经验,此解决方案正常运行(减去我在编辑上述内容时为简洁起见而引入的任何复制/粘贴或拼写错误).

所以,最后,实际问题:

我不喜欢调用者要求使用bind()和_1占位符等.他们真正关心的是:外部类型,内部类型,外部类型获取内部实例的方法,外部类型获取计数内部实例的方法.

有什么方法可以某种方式"隐藏"模板类主体中的绑定吗?我一直无法找到分别为类型和内部方法分别提供模板参数的方法......

谢谢!
大卫

Man*_*agu 2

或者,如果函数具有可预测的签名,您始终可以将函数本身作为模板参数:

template <typename TOuter, typename TInner, 
          TInner& (TOuter::*getfunc)(size_t )>
class ContainerIterator
{
public:
    //...
    TInner& operator*() {return mContainerRef.*getfunc(mIndex);}
    //...
};

template <typename TOuter, typename TInner, 
          size_t (TOuter::*sizefunc)(),
          TInner& (TOuter::*getfunc)(size_t )>
class ContainerProxy
{
public:
    //...
    ContainerIterator<TOuter, TInner, getfunc> end() {
        return ContainerIterator<TOuter, TInner, getfunc>
                   (mContainerRef, 
                    mContainerRef.*sizefunc());
    }
    //...
};

int main()
{
   Bar b;
   ContainerProxy<Bar, Foo, &Bar::size_foo, &Bar::get_foo> proxy(b);
   std::for_each(proxy.begin(), proxy.end(), /*...*/);
}
Run Code Online (Sandbox Code Playgroud)

或者更进一步(http://ideone.com/ulIC7)并通过将函数包装在以下内容中来传递函数std::function

template <typename TOuter, typename TInner>
struct ContainerIterator : public std::iterator<std::input_iterator_tag, TInner>
{
    TOuter& mContainerRef;
    //...
    typedef std::function<TInner& (TOuter*, size_t)> getfunc_type;
    getfunc_type mGetfunc;

    ContainerIterator(TOuter& containerRef, size_t index, getfunc_type const& getFunc)
    /* ... */ {}
    TInner& operator*() {return mGetfunc(&mContainerRef, mIndex);}
    ContainerIterator<TOuter, TInner>& operator++() {++mIndex; return *this;}

    // ...
};

template <typename TOuter, typename TInner>
struct ContainerProxy
{
    TOuter& mContainerRef;

    typedef std::function<size_t (TOuter*)> sizefunc_type;
    sizefunc_type mSizefunc;

    typedef std::function<TInner& (TOuter*, size_t)> getfunc_type;
    getfunc_type mGetfunc;

    ContainerProxy(TOuter& containerRef, sizefunc_type sizefunc, getfunc_type getfunc)
    // ...
    {
    }

    // ...

    ContainerIterator<TOuter, TInner> end() const
    {
        return ContainerIterator<TOuter, TInner>(mContainerRef,
                                                 mSizefunc(&mContainerRef), 
                                                 mGetfunc);
    }
};

int main()
{
    Bar b=...;

    ContainerProxy<Bar, Foo> proxy(b, &Bar::size_foo, &Bar::get_foo); 
    std::for_each(proxy.begin(), proxy.end(), /*...*/);
}
Run Code Online (Sandbox Code Playgroud)