문제

My application implements the visitor pattern. I have several different visitors implementing the same interface and I am trying to decide where the best place to define the visit methods for each of these visitors is.

I at first assumed that it would be best to have a single .cpp file containing all the definitions for a single visitor (one file per visitor). This approach leads to each of the visitor definition files containing quite a lot of #include directives both for the Elements to be visited and any supporting functions that each visit method requires.

Alternatively I can define the visit methods for each visitor in the .cpp files containing the definitions for each element, with this approach the required include directives are already there (and so not repeated) with the exception of the visitors header. The visitor header only contains forward declarations of each of the elements, and so the benefit of this approach is that the number of included headers is reduced overall.

elementa.cpp

#include ...
    ElementA specific stuff.
#include ...

void ElementA::accept(Visitor &visitor) {
    visitor.visit(*this);
}

void VisitorA::visit(ElementA &element)
{
    //do cool stuff
}

void VisitorB::visit(ElementA &element)
{
    //do other cool stuff
}

My question is, is it acceptable/ common to define methods for multiple classes in a single file in this way?

도움이 되었습니까?

해결책

It is highly unusual to put visitor functions in the element class for two reasons

  • It means each visitor's code is dispersed. General rule of thumb is that a class' code is in one place.
  • The entire purpose of Visitor is to decouple the algorithms for the elements. There is no reason to recouple them by putting them in the same .cpp
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top