mardi 2 novembre 2021

How to create begin() and end() for self-define class so that I can use for(T& t: Ts) style in C++

I am learning Composite Design Pattern in C++. I get a problem trying to define a general connect_to function as you can see below. The Layer Class works well due to that it inherits from vector. While the Neuron fails to compile because I implements the begin and end by myself. How can I make it work?

class Neuron;

template<typename Self>
class SomeNeurons {
public:
    template<typename T>
    void connect_to(T& other) {
        //C++11 style
        for (Neuron& from : *static_cast<Self*>(this)) {
            for (Neuron& to : other) {
                from.out.push_back(&to);
                to.in.push_back(&from);
            }
        }
    }
};
class Neuron :public SomeNeurons<Neuron>{
public:
    vector<Neuron*> in, out;
    unsigned int id;

    Neuron() {
        static int id = 1;
        this->id = id++;
    }

//My implementation
    Neuron* beign() {
        return this;
    }

    Neuron* end() {
        return this + 1;
    }

};

class NeuronLayer :public vector<Neuron>, public SomeNeurons<NeuronLayer> {
public:
    NeuronLayer(int count) {
        while (count-- > 0) {
            emplace_back(Neuron{});
        }
    }
};

Aucun commentaire:

Enregistrer un commentaire