Skip to content

Instantly share code, notes, and snippets.

@lzbgt
Last active August 31, 2021 07:00
Show Gist options
  • Save lzbgt/dbea81972953e13d9cce8a22a08405f3 to your computer and use it in GitHub Desktop.
Save lzbgt/dbea81972953e13d9cce8a22a08405f3 to your computer and use it in GitHub Desktop.
#include <vector>
#include <iostream>
using namespace std;
struct Neuron;
template <typename Self>
struct SomeNeurons {
// must be declaration here only
// implementation should be placed at the end
// otherwise there will be 'incomplete type' issue
template <typename T> void connect_to(T& other);
};
struct Neuron : SomeNeurons<Neuron> {
vector<Neuron*> in, out;
unsigned int id;
Neuron()
{
static int id = 1;
this->id = id++;
}
Neuron* begin()
{
return this;
}
Neuron* end()
{
return this + 1;
}
friend ostream& operator<<(ostream& os, const Neuron& obj)
{
for (Neuron* n : obj.in) {
os << n->id << "\t-->\t[" << obj.id << "]" << endl;
}
for (Neuron* n : obj.out) {
os << "[" << obj.id << "]\t-->\t" << n->id << endl;
}
return os;
}
};
struct NeuronLayer : vector<Neuron>, SomeNeurons<NeuronLayer> {
NeuronLayer(int count)
{
while (count-- > 0)
emplace_back(Neuron{});
}
friend ostream& operator<<(ostream& os, NeuronLayer& obj)
{
for (auto& n : obj) os << n;
return os;
}
};
// place template implementation here at the end
template <typename Self>
template <typename T>
void SomeNeurons<Self>::connect_to(T& other)
{
for (Neuron& from : *static_cast<Self*>(this)) {
for (Neuron& to : other) {
from.out.push_back(&to);
to.in.push_back(&from);
}
}
}
int main()
{
Neuron n1;
NeuronLayer l2{2}, l3{3};
n1.connect_to(l2);
l2.connect_to(l3);
cout << "Neuron n1" << endl << n1;
cout << "Layer l2" << endl << l2;
cout << "Layer l3" << endl << l3;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment