There are two simple options that I can think of.
The first option would be the one you describe: create a constructor that takes an object of the other type:
struct UIEvent
{
UIEvent(const Event&);
};
and use std::copy
to copy elements from a vector of one type to a vector of the other:
std::vector<Event> eventVector;
std::vector<UIEvent> uiEventVector;
std::copy(eventVector.begin(), eventVector.end(),
std::back_inserter(uiEventVector));
The second option would be to write a non-member conversion function:
UIEvent EventToUIEvent(const Event&);
and use std::transform
:
std::transform(eventVector.begin(), eventVector.end(),
std::back_inserter(uiEventVector), &EventToUIEvent);
The advantage of doing it this way is that there is less direct coupling between the classes. On the other hand, sometimes classes are naturally coupled anyway, in which case the first option might make just as much sense and could be less cumbersome.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…