实现访问者模式,同时允许不同的返回类型的函数 [英] Implementing Visitor Pattern while allowing different return types of functions

查看:217
本文介绍了实现访问者模式,同时允许不同的返回类型的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现一个对象结构的访问者模式,该结构具有不同返回类型的方法(字符串,signed int,unsigned int等)。

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).

现在,在对象层次结构中,我添加了一个带有以下签名的Accept方法(使用C ++):

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.

推荐答案

类型层次结构中的 Accept 方法只是一个分派器,并且没有返回类型。如果您想要的是访问以产生值,最简单的方法是将其作为访问者状态的一部分添加:

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.

这篇关于实现访问者模式,同时允许不同的返回类型的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆