Implementing Visitor Pattern while allowing different return types of functions

余生长醉 提交于 2019-12-01 13:56:58

问题


I am trying to implement the Visitor Pattern for an object structure which has methods with different return types (string, signed int, unsigned int, etc).

Now, in the object hierarchy I have added an Accept method with the following signature (using C++):

void Accept(Visitor *);

I am unable to figure out how I can use the same interface (with void return type ) while at the same time allowing my concrete methods to have different return types.


回答1:


The Accept method in the type hierarchy is just a dispatcher, and has no return type. If what you want is the visitation to produce a value the simplest way would be to add that as part of the state of the visitor:

struct times2 : visitor {
   double value;
   times2() : value() {}
   void operator()( int x ) { value = x * 2; }
   void operator()( double x ) { value = x * 2; }
};

object o;
times2 v;
o.accept( v );
std::cout << "Result is " << v.value << std::endl;

Then again, the specific details of the visitor will vary with your implementation, but the idea is that you can store the result in the visitor rather than return it.



来源:https://stackoverflow.com/questions/10164714/implementing-visitor-pattern-while-allowing-different-return-types-of-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!