简体   繁体   English

如何在 C++ 中实现返回类型的访客模式

[英]How can I implement the visitor patter with return type in C++

I want to implement the visitor pattern for one of my class without having to depend on the types that will implement the interface to visit them.我想为我的 class 之一实现访问者模式,而不必依赖将实现访问它们的接口的类型。

My solution was this:我的解决方案是这样的:

class model::VisitableNode {
public:
   template<class T>
   virtual T accept(NodeVisitor<T>);
}

But C++ says that it doesn't support template + virtual methods但是 C++ 说它不支持模板+虚拟方法

Node in my application will have only one implementation but if I don't use a template return type my model class will depend on the toolkit that I'm using to create the graphic for my app.我的应用程序中的节点将只有一个实现,但如果我不使用模板返回类型,我的 model class 将取决于我用来为我的应用程序创建图形的工具包。

If a visitor needs to return a value, it is normal to store the returned value in the visitor itself.如果访问者需要返回值,将返回值存储在访问者本身中是正常的。 Thus:因此:

NodeVisitor<double> dv;
node->accept(dv);
double result = dv.result();

If you don't like the boilerplate, you can wrap it in a non-virtual member:如果您不喜欢样板,可以将其包装在非虚拟成员中:

class model::VisitableNode {
public:
   template<class T>
   /* non-virtual */ T accept(NodeVisitor<T>& v) {
      do_accept(v);
      return v.result;
   }
   virtual void do_accept(NodeVisitorBase& v) = 0;
}

Why not template the class itself?为什么不模板化 class 本身?

template<class T>
class model::VisitableNode<T> {
public:
  
   virtual T accept(NodeVisitor<T>);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM