Ports for C++ is a header-only library for creating relations (associations) between classes without sharing their instances.
For detailed examples please look Demos.
Port structure is a simple template class that holds the pointers of given types. After an object registers itself with the Port class, it will become accessible over the target classes. This allows classes to access each others instance indirectly without sharing the instance.
template <class In, class Out>
class Port
{
public:
typedef In InType;
typedef Out OutType;
...
private:
static InPtrType in_ptr;
static OutPtrType out_ptr;
};
Class declares a Port class with itself(to make itself accessible to target class) and target class so Port establishes a two-way relation with given classes.
// ClassA.h
class ClassB; // associated classes can be forward declared.
class ClassA
{
typedef Port<ClassA, ClassB> portB;
public:
ClassA() = default;
...
};
To create this relation successfully Class B also needs to declare the same port with opposite order with template types.
// ClassB.h
class ClassA;
class ClassB
{
typedef Port<ClassB, ClassA> portA;
public:
ClassB() = default;
...
};
All classes that specify In type in the port class must register the object of that type.
// ClassA.cpp
ClassA::ClassA()
{
PortBinder<portB::InType, portB::OutType>::Register(this);
// or register with macro
REGISTER_PORT(portB);
}
// ClassB.cpp
ClassB::ClassB()
{
REGISTER_PORT(portA);
}
After these operations, the relations defined with the Port class can be used as followed
// From ClassA instance to ClassB function call
ClassA::foo()
{
portB::OutPtr()->bar();
// or use port with macro
PORT(portB)->bar();
}
Will be updated.
This library is licensed under the MIT License - see the LICENSE file for details.