Wrapping linked lists in iterators

后端 未结 5 619
青春惊慌失措
青春惊慌失措 2021-01-20 01:21

A set of APIs that I commonly use follow a linked-list pattern:

struct SomeObject
{
    const char* some_value;
    const char* some_other_value;
    SomeObj         


        
5条回答
  •  囚心锁ツ
    2021-01-20 01:34

    From what you said, you probably have a BIG legacy code using your struct SomeObject types but you want to play nicely with new code and use iterators/stl containers.

    If that's the case, you will not be able to (in an easy way) use your new created iterator in all the legacy code base, since that will be changing a lot of code, but, you can write a templated iterator that, if your structs follow the same pattern, having a next field, will work.

    Something like this (I haven't tested nor compiled it, it's just an idea):

    Suppose you have your struct:

    struct SomeObject
    {
        SomeObject* next;
    }
    

    You will be able to create something like this:

    template 
    class MyIterator {
    public:
    //implement the iterator abusing the fact that T will have a `next` field, and it is accessible, since it's a struct
    };
    
    template 
    MyIterator createIterator(T* object) {
       MyIterator it(object);
       return it;
    }
    

    If you implement your iterator correctly, you will be able to use all the STL algorithms with your old structs.

    PS.: If you're in a scenario of some legacy code with this kind of structs, I do too, and I implemented this workaround. It works great.

提交回复
热议问题