Pinco Pinco - 11 days ago 5
C++ Question

Tie two objects

I have to SFML object classes:

Textbox.h
and
ErrorProvider.h
, I defined two objects
TB_Input
(Textbox) and
EP_Note
(ErrorProvider).
When
Textbox
raises
ErrorProvider
it results in a drawn red circle.

I'm trying to tie the two toghether, let me explain:
TB_Input
and
EP_Note
both have to remember they're tied to each other.

The code I have right now:

//Function to tie 2 objects
template<typename ObjectType1, typename ObjectType2>
inline void tie(ObjectType1& obj_1, ObjectType2& obj_2) {
obj_1.tieTo(obj_2);
obj_2.tieTo(obj_1);
}


Pseudo-code for what I need:

// Inside both classes

template<typename ObjectType>
void tieTo(ObjectType link_object) {
<Unknown Type> variable_that_stores_the_tiedTo_object = link_object;
}



Since I the two tied objects can change I can't use fixed type, so I''m using templates.

Answer

By doing more research I found out that the best way is using pointers. Both classes now have an internal void pointer that points to the tied object, I then dereference it and use it as a normal object.

If you need a better idea I'll leave the code here, also feel free to ask me anything.


Button.h:

void tieTo(ObjectType& object) {
    PTR_tiedTo = &object;

    setPosition(object.getPosition().x + object.getSize().x + EP_offset, 
                object.getPosition().y + (object.getSize().y - radius*2)/2);
}

void ErrorProvider::raise(bool value) {
    raised = value;
}


// PTR Definition:
void *PTR_tiedTo;

Textbox.h:

//Same tieTo() function template toghether with this:

void Textbox::setEP(bool value) {
    ErrorProvider *EP_ptr = static_cast<ErrorProvider*>(PTR_tiedTO);
    EP_ptr->raise(value);
}
Comments